Showing posts with label Value Type. Show all posts
Showing posts with label Value Type. Show all posts

Tuesday, May 28, 2013

Value Type Vs Reference Type

In .Net any variable / object falls under one of the types Value Type or Reference Type, by default structs are value type and classes are reference type. 

The following are some of the key difference between value type and reference type variables / objects.

Value Type

Value Type variables are those which have a separate memory segment allocated for them, when a value type variable is copied to another value type variable each variable has its own memory segment and changes done to one of the variable does not affect the value of the other.

All value type variables are implicitly derived from System.ValueType

Sunday, May 26, 2013

What is a Struct?

Structs can be used to define custom types, which are build using a combination of the primitive types like int, string etc. For example we can define an Employee Struct which can hold details of the employee id, name, address etc in individual types like int, string etc.

Structs are value types while classes are reference types, which means that every instance of the Struct is completely independent and have their own set of values. If a struct instance A is assigned to struct instance B then both A & B have their own memory and have an independent set of value, hence any change to instance A will not affect instance B.

The below example defines a simple Struct which contains an integer id and a string name representing an employee details.