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. Bothxandstudentare referring to the same object, but the type of thexvariable means that only the members defined onIRegisterare available.You then create a third reference to the same object and assign that to
newstudent. Sincenewstudentis of typeStudent, you can access all of the member ofStudentfrom 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.