Types
-
date_range 27/12/2017 00:00 infosortIntroductionlabelTypes
Reference Types
A reference type contains a pointer to another memory location that holds the data. When ever we are creating a class we are creating a reference type variable. It is a reference or pointer that will tell runtime complier where to find value stored in the memory.
Value Types
A value type holds the value of the variable itself. Value types are faster to allocate memory and occupies lot less space when compared to refernce types. Value types are immuatable which means we can’t change the value of a type. For instance if we change an integer from say 3 to 4 but value of 4 can’t be changed.
[TestMethod]
public void intTest()
{
int x2=20;
int x1=x2;
x2=30;
Assert.NotEqualto(x1,x2); // True
}
The above snippet confirms what we just said about value types.
Creating Value Types
public Struct DateTime
{
..
}
Even though the above struct can hold many values like CurrentDay, CurrentYear and so on this is conceputally represented as single value and it points to single value. For more about structs.
public Enum PayrollType
{
contractor=1,
salaried=2
}
Whereas Enum creates variables that will hold only specific numeric values. Its also a recommended way to create constants in a software.
public (Employee.Role==PayrollType.salaried)
{
...
}
Above PayrollType
can be used to determine the salary of the employee and other amenities for the employees. Each of the varibles in
Enum will have an integer value. By default the first value will always be zero. If values of the other variables were not specifiyed
then it will automatically have the values of 1,2,3 and so on. Enum doesn’t require any instantiation like object types.
Method Parameters
In C# default is pass by value which means reference type passes a copy of reference variable while values type passes a copy of value.
Unless the keyword ref
is used always a copy will be passed.
public void Increment(int n)
{
n+=1;
}
[TestMethod]
public void PassByValue(int x)
{
int x=22;
increment(x);
Assert.areEqual(x,22); //True
}
Since a copy of is being passed as parameter it doesn’t change the value of x itself.
public void AddName(GradeBook Book)
{
book.Name='Gef Bool';
}
[TestMethod]
public void PassByReference()
{
GradeBook book1=new GradeBook();
GradeBook book2=book1;
AddName(book2);
Assert.areEqual("Gef Bool",book1.Name); //True
}
This will return true since pointer of book1/book2 can’t change the pointer of book and since a copy of book2 is being passed to book which means all the objects are holding the pointer to same variable.
Eventhough it changes the values of variables this is same as int method as we saw earlier since it can’t change pointer of either book1 or book2.
Ref and Out Parameters
[TestMethod]