basic difference between value types and reference types

31,145

Solution 1

Consider two variables:

SomeReferenceType x;
SomeValueType y;

The value of x is a reference - it will either be null or a reference to an object which is itself an instance of SomeReferenceType or a derived class. The value of x is not, in itself, the object.

The value of y is the data itself - if SomeValueType has three fields, the value of y will directly contain those fields.

That's a very brief summary - see Eric Lippert's blog post about value types and my article for more information. (You might also be interested in my article about parameter passing which is related, but not quite the same.)

Solution 2

Value types, as name tells, are values stored in memory; referencer types are (a kind of) pointer to an object (a class, an object, etc...)

From Microsoft:

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

Solution 3

Variables of reference types, referred to as objects, store references to the actual data, see here for details. They include classes, interfaces and delegates.

From MSDN:

Value Types are structs and enumerations. Variables that are based on value types directly contain values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself. All value types are derived implicitly from the System.ValueType. Unlike with reference types, you cannot derive a new type from a value type. However, like reference types, structs can implement interfaces. Unlike reference types, a value type cannot contain the null value. However, the nullable types feature does allow for values types to be assigned to null

Read this: http://www.csharptocsharp.com/node/41

Solution 4

When you have a variable of a value type, that variable directly holds a value. If you assign it to another variable, the value is copied directly. When the variable is of a reference type, it does not hold the value directly, but rather a reference (a pointer) to the value. When you copy the variable, you don't copy the value that it points to, but the reference (pointer).

You can read more about in MSDN: http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx and http://msdn.microsoft.com/en-us/library/490f96s2.aspx

Share:
31,145
Admin
Author by

Admin

Updated on July 05, 2022

Comments