28 June, 2009

Value types VS Reference types C#

What is difference between Value types and Reference types in VB.NET or C# (Value types VS Reference types)

C# provides two types—class and struct, class is a reference type while the other is a value type. Here is difference between Value types and Reference types.

Value types directly contain their data which are either allocated on the stack or allocated in-line in a structure. Reference types store a reference to the value's memory address, and are allocated on the heap. With reference types, an object is created in memory, and then handled through a separate reference—rather like a pointer.

Reference types can be self-describing types, pointer types, or interface types. Primitive types such as int, float, bool and char are value types.

Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable.

Value types have a default implied constructor that initializes the default value. Reference types default to a null reference in memory.

Value types derive from System.ValueType. Reference types derive from System.Object.

Value types cannot derive a new type from an existing value type, except for structs. Reference types can derive a new type from an existing reference type as well as being able to implement interfaces.

No comments: