Reference Types:
variables store reference to a type.
we will see some scenarios :
scenario1:
class student
{
public int id { get;set;}
}
//'s1' is a variable of type 'student'
student s1 = new student();
//Assign value of s1 to s2 .(value of s1 is address of student object)
student s2 = s1;
s1.id = 23;
// since s1 and s2 are referring same student object, s1.id and s2.id contains same value.
Console.WriteLine("s1 " + s1.id + " s2 " + s2.id );
o/p : s1 23 s2 23
scenario2:
//'s1' is a variable of type 'student'
student s1 = new student();
//Assign value of s1 to s2 .(value of s1 is address of student object)
student s2 = s1;
s1.id = 34;
//creating second instance of student object.
s1 = new student();
s1.id = 23;
// s2 is still referring to old student object, but s1 is now referring new student object, hence s1 and s2 holds
different values
Console.WriteLine("s1 " + s1.id + " s2 " + s2.id );
o/p : s1 23 s2 34
Value Types:
Variables holds value.
int x1 = 10;
//Assign value of x1 to x2(value of x1 is 4 not the address of 4)
int x2 = x1;
x1 = 23;
// since x2 holds value of x1, even if we initialize x1 value to 23 the value of x2 does not change to 23.
Console.WriteLine(x2);
o/p: 10
variables store reference to a type.
we will see some scenarios :
scenario1:
class student
{
public int id { get;set;}
}
//'s1' is a variable of type 'student'
student s1 = new student();
//Assign value of s1 to s2 .(value of s1 is address of student object)
student s2 = s1;
s1.id = 23;
// since s1 and s2 are referring same student object, s1.id and s2.id contains same value.
Console.WriteLine("s1 " + s1.id + " s2 " + s2.id );
o/p : s1 23 s2 23
scenario2:
//'s1' is a variable of type 'student'
student s1 = new student();
//Assign value of s1 to s2 .(value of s1 is address of student object)
student s2 = s1;
s1.id = 34;
//creating second instance of student object.
s1 = new student();
s1.id = 23;
// s2 is still referring to old student object, but s1 is now referring new student object, hence s1 and s2 holds
different values
Console.WriteLine("s1 " + s1.id + " s2 " + s2.id );
o/p : s1 23 s2 34
Value Types:
Variables holds value.
int x1 = 10;
//Assign value of x1 to x2(value of x1 is 4 not the address of 4)
int x2 = x1;
x1 = 23;
// since x2 holds value of x1, even if we initialize x1 value to 23 the value of x2 does not change to 23.
Console.WriteLine(x2);
o/p: 10
No comments:
Post a Comment