This is such a difficult question to explain online but I shall try my best. I have instantiated an object of type B which is stored in a variable of type A. I use the get type property, so now it is type B. Have I therefore performed an implicit conversion of type A and B. So therefore when a.show() is called is it of type B?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class A
{
public virtual void show()
{
Console.WriteLine("Showing A");
}
public void test()
{
Console.WriteLine("called from A");
}
}
class B:A
{
public override void show()
{
Console.WriteLine("Showing B");
}
public void testb()
{
Console.WriteLine("called from B");
}
}
class Program
{
static void Main(string[] args)
{
A a = new B();
// Outputs ConsoleApplication.B
Console.WriteLine("{0}", a.GetType());
// outputs showing B
a.show();
// outputs called from A
a.test();
Console.ReadLine();
}
}
}
You haven’t performed an implicit conversion as you haven’t actually converted anything.
You have directly instanciated an object of type B. You can reference it from a variable of type A because B is a sub class of A. However, the two actions should be considered as independant.
… = new B();
will always instanciate an object of type B, regardless of what is on the left.
Will always try to assign what is on the right to the variable a.
The only difference that the type of the reference will make is in how the object is seen by the CLR.
Both are objects of type B. However, ‘a’ will only allow you to work with it as if it were an object of type A. So, you can only call a.show() and a.test(), even although it is actually of type B and so does have the additional method testb(). ‘b’ will allow you to call b.show(), b.test() and b.testb(). Regardless of the variable type, when you call show(), it is of type b and so it is the overriden show() method that is returned.
Finally, what you can now do is downcast. i.e. you instanciated an object of type B so you can now cast it to a variable of type b and so allow full access to all of type B members.
e.g.:
I just saw you additional question of why would you want to instanciate something as type A, i.e. the base class. This is to provide a common ground as a way of working with objects of different types. For example, you may have a base type of Animal and derrive from it several sub classes – Cat, Dog, Gerbil. However, you may then want to be able to pass a list of all Animals to a method that only needs to work with common properties. So, if Animal had a name, your List could be iterated and each Animals name referred to, even although Animal could itself be Abstract (Not able to be instanciated) and the list comprise entirely of Dogs, Cats and Gerbils. You can also then downcast the various animals by finding out what there type is to interact with them further, e.g.
Or you could use the ‘as’ keyword to do the cast:
Hope this helps.