Sunday, February 7, 2010

Differences between Struct And Class

Structs are value types.
classes are reference types.

A data type is a value type if it holds the data within its own memory allocation.
A reference type contains a pointer to another memory location that holds the data.

Value Types
-------------
Value types include the following:
All numeric data types
Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations, since their underlying type is always SByte, Short,
Integer, Long, Byte, UShort, UInteger, or ULong

Reference Types
-----------------
Reference types include the following:
String
All arrays, even if their elements are value types
Class types, such as Form
Delegates


class Program
{
 static void Main(string[] args)
 {
  #region Reference type Class
   productInfo pinfo1 = new productInfo();
   productInfo pinfo2 = new productInfo();
   pinfo1.productName = "Product One";            
   pinfo2 = pinfo1;
   Console.WriteLine("pinfo1.productName :" + pinfo1.productName);
   Console.WriteLine("pinfo2.productName :" + pinfo2.productName);
   pinfo2.productName = "Product Two";
   Console.WriteLine("pinfo1.productName :" + pinfo1.productName);
   Console.WriteLine("pinfo2.productName :" + pinfo2.productName);
  #endregion            

  Console.WriteLine("--------------------------------");

  #region Value type Struct
   customerInfo cus1 = new customerInfo();
   customerInfo cus2 = new customerInfo();
   cus1.customerName = "Customer One";
   cus2 = cus1;    
   Console.WriteLine("cus1.customerName :" + cus1.customerName);
   Console.WriteLine("cus2.customerName :" + cus2.customerName);
   cus2.customerName = "Customer Two";
   Console.WriteLine("cus1.customerName :" + cus1.customerName);
   Console.WriteLine("cus2.customerName :" + cus2.customerName);
  #endregion

  Console.Read();
 }
}

public class productInfo
{
 private string _productName;
 public string productName
 {
  get { return _productName; }
  set { _productName = value; }
 }
}

public struct customerInfo
{
 private string _customerName;
 public string customerName
 {
  get { return _customerName; }
  set { _customerName = value; }
 }
}



Output Value is :
pinfo1.productName :Product One
pinfo2.productName :Product One
pinfo1.productName :Product Two
pinfo2.productName :Product Two
--------------------------------
cus1.customerName :Customer One
cus2.customerName :Customer One
cus1.customerName :Customer One
cus2.customerName :Customer Two





View More here

No comments:

Post a Comment