static void Main(string[] args)
{
Student student = new Student()
{
ID = 12,
Name = "Manu",
LastName = "Shekar"
};
Iregister x = student;
Student newstudent = x as Student;
//Console.WriteLine(x.LastName); //Uncommenting this shows compilation error
Console.WriteLine(newstudent.LastName); //This Show "Shekar"
Console.ReadKey();
}
class Student : Iregister
{
public int ID { get; set; }
public string Name { get; set; }
public String LastName { get; set; }
}
interface Iregister
{
int ID { get; set; }
String Name { get; set; }
}
I wonder how the newstudent.LastName
gets the correct value since it is casted from Iregister
which doesn't have LastName
property?
How the value "Shekar" is passed from student.LastName
to newstudent.LastName
. Did x
stores it somewhere in between? Pardon me if i miss something basics.
You create a single object, and assign a reference to it in the variable
student
.You then create a second reference to the same object and assign that to
x
. Bothx
andstudent
are referring to the same object, but the type of thex
variable means that only the members defined onIRegister
are available.You then create a third reference to the same object and assign that to
newstudent
. Sincenewstudent
is of typeStudent
, you can access all of the member ofStudent
from that reference.Not that the variables just store references. It's the object that stores its own actual data, and that object remained unchanged throughout the process.