C# Simplified - Value Types and Reference Types
(Page 3 of 5 )
The data types in C# can be classified as Value Types and Reference Types. Value Types include all numerical data types such as Integer, Float, Byte and Decimal, etc. and you work directly with values. If you try to assign one value type to another, a bit wise copy is achieved. Listing 1.3 illustrates this concept in detail:
Listing 1.3
001: // Valtype.cs
002: // -----------
003: using System;
004: struct Valdata
005: {
006: public int a;
007: public int b;
008: }
009:
010: class Valtype
011: {
012: public static void Main(string[] args)
013: {
014:
015: // Object of the Structure created
016: Valdata v = new Valdata();
017: v.a = 500;
018: v.b = 600;
019:
020: // A new variable named v1 created and passed the value of structure object
021: Valdata v1 = v;
022:
023:
024: //Prints 500
025: Console.WriteLine(v.a);
026:
027: //Prints 600
028: Console.WriteLine(v.b);
029:
030: // Prints 500
031: Console.WriteLine(v1.a);
032:
033: // Prints 600
034: Console.WriteLine(v1.b);
035:
036: Console.WriteLine("After Changing the value of one variable");
037:
038: v1.a = 900;
039:
040: // Prints 900
041: Console.WriteLine(v1.a);
042:
043: //Prints 500
044: Console.WriteLine(v.a);
045: }
046: }
From the above code, you will notice that if you change the value of one variable, the value of another variable will not change. The output of the above program looks like Figure 1.1.

Figure 1.1
Reference types are just opposite of Value types. Classes and Interfaces are reference types. If you change the value of one variable the value of the other variable also reflects the same value. Listing 1.4 is a modified version of listing 1.3:
Listing 1.4
001: // Reftype.cs
002: // ----------
003: using System;
004: class Valdata
005: {
006: public int a;
007: public int b;
008: }
009:
010: class Reftype
011: {
012: public static void Main(string[] args)
013: {
014:
015: // Object of the Structure created
016: Valdata v = new Valdata();
017: v.a = 500;
018: v.b = 600;
019:
020: // A new variable named v1 created and passed the value of structure object
021: Valdata v1 = v;
022:
023:
024: //Prints 500
025: Console.WriteLine(v.a);
026:
027: //Prints 600
028: Console.WriteLine(v.b);
029:
030: // Prints 500
031: Console.WriteLine(v1.a);
032:
033: // Prints 600
034: Console.WriteLine(v1.b);
035:
036: Console.WriteLine("After Changing the value of one variable");
037:
038: v1.a = 900;
039:
040: // Prints 900
041: Console.WriteLine(v1.a);
042:
043: //Prints 900
044: Console.WriteLine(v.a);
045: }
046: }
From the above listing, you will understand that even if you change the value of one variable, the value of other variable also changes (see lines 038 to 044). The output of the above program looks like Figure 1.2

Figure 1.2
Next: Boxing and Unboxing >>
More C# Articles
More By Anand Narayanaswamy