Class—A
class ClassA
{
public string c1()
{
return "Class-A";
}
}
Class—B
class ClassB:ClassA
{
public string c2()
{
return "Class-B";
}
}
Main Class
—–Part 1——————
ClassA obj1 = new ClassB();
string a = obj1.c1();//Here i will get only c1
Console.WriteLine(a);
Console.ReadLine();
—–Part 2——————
ClassB obj1 = new ClassA();
string a = obj1.c2();//Her i will get both c1 and c2
Console.WriteLine(a);
Console.ReadLine();
In Part-1,i will get only c1.I need to know whether variable (obj) is created for ClassA in stack and assign address of ClassB from Heap.What is actually happening?
In Part -2 ,Getting(compilation error) conversion error.What is actually happening behind the screen while executing this code.
Thanks,
Joby Kurian
Part 1
This creates an instance of
ClassB– an object.It also declares a variable called
obj1, of typeClassA. That variable’s value will always be a reference – eithernullor a reference to an instance ofClassA. In this case, the initial value is a reference to the newly createdClassBobject. (A reference to aClassBobject can be used as aClassAreference too, becauseClassBderives fromClassA.)When you call
c1, it just calls the implementation inClassA– but within that method, if you printed outthis.GetType()it would still returnClassB‘s type, as it’s operating “within” aClassBobject.I strongly suggest you don’t worry about the stack and the heap yet. Focus on the three different concepts:
Eric Lippert has blogged a lot about this sort of thing. You might want to start with The Stack Is An Implementation Detail.
Part 2
This creates an instance of
ClassA, and tries to assign a reference to the new object to a variable of typeClassB. That doesn’t work, becauseClassAdoes not derive fromClassB. You can’t use a reference of compile-time typeClassAto a variable of typeClassB. As a demonstration of why this wouldn’t work, it’s a bit like doing this:Basically, inheritance doesn’t work that way round – you can treat an instance of
ClassBas an instance ofClassA(in most cases) but you can’t treat an instance ofClassAas an instance ofClassB. You’d normally be adding more state (fields) inClassB, so that information just wouldn’t be present in the instance ofClassA.