Home > database >  What is the effect of instantiating the object from the subclass?
What is the effect of instantiating the object from the subclass?

Time:02-14

    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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related