Value Types and Reference Types (Page 1 of 4 )
C# is a language where every variable that you declare must have a type. A type is defined as a set of data and the operations performed on them. It is used when declaring local variables, classes, interfaces, arrays, structures and so on. When writing applications, you can use the types already provided by C#, like
int,
long, and
System.Environment, or you can create your own (
Employee,
Book,
Invoice). But in either case, the types come in two different flavors: value types and reference types.
Value Types: A value type is either a simple type (bool,char,sbyte,byte,short,ushort,int,uint,long,ulong,float,double,decimal), astructtype, or anenumtype. A variable of a value type contains the data (as opposed to holding the address that shows where the data actually is). For example, the following declaration...
intcount = 104;
will be interpreted as:

The memory location for the variable count contains the value 104.
Assigning a value of value type to a variable of value type makes a copy of the value. Try the following code:
class Program
{
static voidMain(string[] args)
{
intcount = 104;
Console.WriteLine("Value of count is: {0}", count);
intanotherCount = count;
Console.WriteLine("Value of anotherCount is: {0}", anotherCount);
}
}
This will result in the following:

Seeing as structures and enumerations are value types as well, the same idea applies. Ponder the following example:
class Program
{
static voidMain(string[] args)
{
Pointp;
p.x = 2;
p.y = 7;
Console.WriteLine(p);
Pointp2 = p;
Console.WriteLine(p2);
}
}
struct Point
{
public intx;
public inty;
public override stringToString()
{
return string.Format("[{0},{1}]", x, y);
}
}
Notice that [2,7] is printed for both structures.
Next: Passing Value Types >>
More C# Articles
More By Ayad Boudiab