Sponsored Ad

Wednesday, September 16, 2009

.NET C# Data Types

C# is a strongly typed language and as such all variables and objects must have a declared data type. The data type can be one of the following:

  1. Value
  2. Reference
  3. User – defined
  4. Anonymous

Value Types

A value type variable contains the data that it is assigned. For example, when you declare an int (integer) variable and assign a value to it, the variable directly contains that value. And when you assign a value type variable to another, you make a copy of it. The following example :
class Program1
{
static void Main(string[] args)
{
int intnum1, intnum2;
intnum1 = 5;
intnum2 = num1;
Console.WriteLine(“num1 is {0}. num2 is {1}”, intnum1, intnum2);
intnum2 = 3;
Console.WriteLine(“num1 is {0}. num2 is {1}”, intnum1, intnum2);
Console.ReadLine();
return;
}
}


The output of this program is:
num1 is 5. num2 is 5
num1 is 5. num2 is 3

Reference Types



For reference types, the variable stores a reference to the data rather than the actual data. Consider the following:
Button btnTest1, btnTest2;
btnTest1 = new Button();
btnTest1.Text = “YES”;
btnTest2 = btnTest1;
Console.WriteLine(“{0} {1}”, btnTest1.Text, btnTest2.Text);
btnTest2.Text = “NO”;
Console.WriteLine(“{0} {1}”, btnTest1.Text, btnTest2.Text);

Here, you first declare two Button controls — btn1 and btnTest2 . btnTest1 ’ s Text property is set to “ YES” and then btnTest2 is assigned btnTest1 . The first output will be:
YES YES

When you change btnTest2 ’ s Text property to “ NO” , you invariably change btnTest1 ’ s Text property, as the second output shows:
NO NO

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers