class Dog
{
}
class BullDog : Dog
{
}
class Program
{
static void Main()
{
Dog dog2 = new BullDog();
BullDog dog3 = new BullDog();
}
}
>
Q: "What is the difference between using Dog as a reference vs BullDog as a reference?"
A: If you have a Dog reference, any additional methods/properties/fields you add to the derived type BullDog will not be publicly accessible.
E.g. if you had:
public class Dog
{
public virtual void Bark()
{
Console.WriteLine("Woof");
}
}
public class BullDog : Dog
{
public override void Bark()
{
Console.WriteLine("BOWF!");
}
public void Slobber()
{
Console.WriteLine("I cannot control my drool :(");
}
{
... you wouldn't be able to do this:
Dog baseDog = new BullDog();
baseDog.Slobber(); // error -- Dog doesn't know how to slobber.
... as the method doesn't exist for the base type.
Also, depending on whether you have a base/derived reference, there are also some subtle problems that can occur if you carelessly use the new operator. However, these are very rare occurrences in my experience (see Wouter de Kort's post, as he just posted a better explanation as I was typing it up).
Q: "I have an habit of using var dog3 = new BullDog(); which is similar to BullDog dog2 = new BullDog(); When do we need to use Dog dog2 = new BullDog();?"
A: You may not even know what type of Dog
you're getting, all you know is .. it's a Dog
. Consider...
public static class DogFactory
{
public static Dog CreateMysteryDog()
{
return new Shitzu();
}
}
Dog dog = DogFactory.CreateMysteryDog(); // what is the concrete type of Dog?
DogFactory returns a Dog
reference, not a Shitzu
reference, so you have to use the base type. In this case, var will be a Dog
rather than a Shitzu
, too.