Friday, October 1, 2010

Understanding the Types in C#

C# supports two kinds of types:
Value types and reference types:Value types include simple types (e.g., char, int, and float), enum types, and struct types. Reference types include class types, interface types, delegate types, array types.
Value types differ from reference types in that variables of the value types directly contain their data, whereas variables of the reference types store references to objects. With reference types, it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data and it is not possible for operations on one to affect the other.

The example:

Class class1
{
Public int value = 0;
}
Class Test
{
Static void main( )
{
Int val1 = 0;
Int val2 = val1;
Val2 123;
Class1 ref1 = new class1 ( );
Class1 ref2 = ref1;
Ref2.value = 123;
Console.writeLine(“values: {0}, {1}” , val1, val2);
Console.writeLine(“Refs: {0} , {1}” , ref1.value, ref2.value);
}
}

Shows this difference output produced is.
Values: 0 , 123
Refs: 123 , 123

Note: - The assignment to the local variable val1 does not impact the local variable val2 because both local variables are of a value type(the type int) and each local variable of a value type has its own storage. In contrast, the assignment ref2.value = 123; affects the object that both ref1 and ref2 reference.

No comments:

Recent Posts