Monday, May 21, 2012

Value Types in C#

There are two types of Data types in C#, Value types and Reference types.  Value types are those variables which can directly assigned a value with. Few examples are 

a. Structs
b. Enums
c. Primitive(Simple) data types like Int, Char

When a value type variable is assigned to another variable, value associated with that variable is assigned to other unlike reference types where reference is copied.

System.Object is base class for any type in .NET.

Quick Points about Value Types:
  1. Value types are allocated on Stack
  2.  All Value Types derive implicitly from System.ValueType class, which derives System.Object which is base for any type.  We cannot create a class that inherits from ValueType. 
  3. Value types can implement interfaces. e.g. structure can implement interfaces.
  4. Each default will have a default value. When struct is instantiated with default values for each of its member.
  5. ValueType class overrides few methods of System.Object class.
Even Value types can be defined with new operator, though it is very rare we use such a statement.

int i = new int();
It is same as creating a variable of type and assigning it to default value. 
int  i = 0; // creates and assigns value 0 to i


No comments:

Post a Comment