Value types are derieved from two main categories Structs & Enumerations.
Structs fall into the following categories
- Integral types
- Floating-point types
- decimal
- bool
- User defined structs
Value types are contained on the stack , assigning one value type variable to another copies the
contained value. This differs from reference types, which are stored on the managed heap and
copying a reference type copies the reference to the object but not the object itself.
Console.WriteLine("a = {0}", a);
Console.WriteLine("b = {0}", b);
a = b;
b = 4;
Console.WriteLine("a = {0}", a);
Console.WriteLine("b = {0}", b);
The variable a starts off with a value of 1 and b with a value of 2.
The contents of variable b are copied to a and variable b set to 4.
However changing variable b does not affect variable a, which has
a copy of the contents of variable b.
All value types are derieved from System.ValueType one interesting type is System.String this doesn't derieve from System.ValueType but acts like a value type, it is immutable a new instance is created
each time it is changed unlike other reference types.
string a = "first string";
string b = "second string";
Console.WriteLine("string a = {0}", a);
Console.WriteLine("string b = {0}", b);
b = a;
a = "modified string a";
Console.WriteLine("string a = {0}", a);
Console.WriteLine("string b = {0}", b);
Unlike reference types, it is not possible to derieve a new type from a value type. However, like reference types, structs can implement interfaces.
No comments:
Post a Comment