ismet
ismet

Reputation: 39

What is the effect of instantiating the object from the subclass?

    public class BaseClass
    {
        public string Name { get; set; }
    }

    public class SubClass : BaseClass
    {
        public decimal Price { get; set; }
    }
    BaseClass o1 = new SubClass();
    SubClass o2 = new SubClass();

    Console.WriteLine(o1.GetType().Name);
    Console.WriteLine(o2.GetType().Name);

Outputs are

    SubClass
    SubClass

What is the main difference between o1 and o2? In which cases is it necessary to define an object with BaseClass and instantiate it with SubClass?

Upvotes: 0

Views: 550

Answers (2)

pm100
pm100

Reputation: 50190

The big difference is evident when you try this

BaseClass o1 = new SubClass();
SubClass o2 = new SubClass();
var name1 = o1.Name; // works
var price1 = o1.Price; // wont compile
var name2 = o2.Name; // works
var price2 = o2.Price; // works

This is becuase BaseClass doesnt have Price

Upvotes: 1

Felix
Felix

Reputation: 10078

In the context of your question the type of the variable is irrelevant. For a more common example, you can have an interface:

interface IExample { ... }

and a class that implements the interface:

class Example : IExample { ... }

Obviously, if you manually instantiating the variable, or if you are using DI, it would have the class; but you typically assign it to the interface type:

IExample ex = new Example();

But any reflection tool will show you actual class.

Upvotes: 0

Related Questions