21 Mar, 2009 · 7 minutes read
In C#, Variables are either value types or reference types depending on what they store, values or references. By reference we imply that the variable holds the memory address of another location where the actual value is stored. All built in data types – Int, Char, String, Float, Boolean, etc are value types while classes are reference types. The following is a diagrammatic representation of these two types.
In this picture there are two variables Num1 and Num2. Both of these being integer variables store the values directly.
The two variables in this case are actually objects of a car class. As you can see, they do not store the values directly but only a pointer to the memory location where the value is actually stored.
Consider the following code snippet:-
int Num1, Num2;
Num1 = 100;
Num2 = Num1;
Num1 ++;
Console.WriteLine("Num1={0}", Num1);
Console.WriteLine("Num2={0}", Num2);
Here we declare two integer variables, Num1 and Num2. On line 2 we set the value of Num1 to 100 and at line 3, we copy the value of Num1 to Num2. Both Num1 and Num2 now store 100. In the next line, we increment the value of Num1 by 1, thus it stores 101 now. This doesn’t make any change in the value of Num2 as both of them are value types and have a separate storage location in the memory. Finally, we display the numbers and the output comes as:-
Num1=101
Num2=100
Now take a look at this code snippet:-
Car Ferrari, McLaren;
Ferrari = new Car("F2004");
McLaren = Ferrari;
McLaren.Model = "F2002";
Console.WriteLine("Ferrari={0}", Ferrari.Model);
Console.WriteLine("McLaren={0}", McLaren.Model);
Two objects of the Carclass are declared. We instantiate Ferrari by using the new keyword, passing the value F2004to its constructor which sets the Modelto F2004. The third line McLaren = Ferrari;copies the value stored by the object Ferrari to McLaren. All classes being reference types, the objects store the memory address of the actual storage location. Hence, by copying Ferrari to McLaren, we are actually copying the memory location. Now both Ferrari & McLaren are pointing to the same physical location in the memory. In the next line, the model for the McLaren is changed to F2002. This doesn’t make any change to the value stored by the McLaren object, i.e the memory address. The change occurs in the storage location pointed to by the McLaren object. Since, Ferrari is pointing to the same memory location this change reflects there as well and the results of the last two lines are:-
Ferrari=F2002
McLaren=F2002
A structure is a value data type which is used to group related heterogeneous data types. Say you want to store the details of all the employees of your company such as – Name, Post, Salary, Joining Date, etc. In such a scenario we can create a structure named employee which would be composed of these fields. We use the structkeyword to create structures with the following syntax:-
struct StructureName
{
member variable 1
member variable 2
…
}
Structures are similar to classes in the sense that they contain data members and functions, have access specifiers and need to be instantiated, but they do have notable differences such as:-
Example Usage:-
struct Employee
{
public string Name;
public string Post;
public int Salary;
public string JoiningDate;
}
static void Main(string[] args)
{
Employee Emp1 = new Employee();
Console.WriteLine("Enter Employee's Name");
Emp1.Name = Console.ReadLine();
Console.WriteLine("Enter Employee's Post");
Emp1.Post = Console.ReadLine();
Console.WriteLine("Enter Employee's Salary");
Emp1.Salary = Console.ReadLine();
Console.WriteLine("Enter Employee's Joining Date");
Emp1.JoiningDate = Console.ReadLine();
}
Note: Unlike in other languages such as C/C , structures in C# can have member functions.
Enumeration is another value data type that we use to store non generic values such as the name of the day – Sunday, Monday, etc. One may question the need for enumeration considering that we can use the string data type to store the names. But, one could assign just about any value to the day, which we certainly don’t want. We could also use the numbers from 0 – 6 to denote the 7 days. However, that doesn’t clarify whether 0 is for Sunday or Saturday. The enumkeyword is used to create an enumerated data type with the following syntax:-
enum EnumDataType { Value1, Value2, and so on }
Example usage:-
enum Month { Jan, Feb, Mar, Apr, May, Jun, Aug, Sep, Oct, Nov, Dec };
static void Main(string[] args)
{
Month ThisMonth;
ThisMonth = Month.May;
}
Note:- The values of an enumerated data type are assigned in design time and not at runtime using the Console.Read or Console.ReadLine method.
An array is a collection of values of the same data type, grouped under the same name and referred to by their distinct indexes. This is how they are represented in the memory.
Declaration
Syntax:-
datatype[] ArrayName;
Example usage:-
int[] Marks;
Initialization
Memory is allocated to the array only when it is instantiated. The instantiation can be done in the following methods. Once initialized a default value is assigned to all of the elements depending on their data type – 0 for int, “” (NULL String) for char or string, etc.
Syntax:-
ArrayName = new datatype[size];
This step can be done along with the declaration.
datatype[] ArrayName = new datatype[size];
Example Usage:-
int[] Marks = new int[10];
Note: This creates 10 elements starting from 0 to 9
Assigning values
Each element of the array can be accessed by specifying their index along with the ArrayName.
ArrayName[index] = value;
Example:-
Marks[5] = 99;
Values can also be assigned during declaration as follows:-
datatype[] ArrayName = {value1, value2, value3 and so on};
Example:-
int[] Marks = {100, 13, 69, 99};
Using this process implicitly sets the size for the array. In this case it would be 4. The elements can be accessed by their indexes starting from 0 to 3. Note: In C# Index always starts at 0.
Using the following is equivalent to using the above line of code.
int[] Marks = int[4] {100, 13, 69, 99};
Copying an Array
You can copy an array just as easily you copy other variables. Example:-
int[] Source = {0, 1 , 2, 3, 4};
int[]Destination = Source;
One point to note is that an array being a reference type, both these arrays point to the same location in memory and any change made in either of them would be reflected in the other one as well. To make separate copies of the array, we need to copy each of the elements individually. The code below does just that.
int[] Source = { 0, 1, 2, 3 };
int[] Destination = new int[Source.Length]; // Set the size of the destination to be the same as that of the source
for (int I = 0; I < Source.Length; I )
{
Destination[I] = Source[I];
}
This step can be done along with the declaration.
datatype[] ArrayName = new datatype[size];
Example Usage:-
int[] Marks = new int[10];
Note: This creates 10 elements starting from 0 to 9