Senator Guerra Souty original series calendar,replica hublot blue steel peach pointer collocation of rolex replica Rome digital scale, track type minute replica watches scale shows that the classical model is swiss replica watches incomparable, wearing elegant dress highlights.
mr-ponna.com

 

YOU ARE HERE: HOME Questions if class a is inherited by class b and class b is inherited by class c Now i have an instance of



Create instance of its base type

View(s): 8251

if class a is inherited by class b and class b is inherited by class c. Now i have an instance of class c, from this instance can i create an instance of class a. if yes, how?

Answer 1)

Formated Version:
If class A is inherited by class B and class B is inherited by class C. Now I have an instance of class C, from this instance can I create an instance of class A. if yes, how?

Yes, we can create instance of its base types from derived class instance. But only constraint is the Base class should not be abstract class or interface.

Using Type.BaseType and Activator.CreateInstance, we can achieve above functionality.

Here sample code:

class Program
{
    static void Main(string[] args)
    {
        C objC = new C();
        Type baseBType = objC.GetType().BaseType; // gets it’s parent type, here it is class B type
        Type baseAType = baseBType.BaseType; // again get parent for B type, which is A type
        object objA = Activator.CreateInstance(baseAType); // create a instance uisng Type.
    }
}

class A
{
    public int I;
}

class B : A
{
    public int J;
}

class C : B
{
    public int K;
}

  Asked in:  Inooga Solutions   Expertise Level:  Experienced
  Last updated on Saturday, 19 May 2012
4/5 stars (8 vote(s))

Register Login Ask Us Write to Us Help