0

Let's say I have a parent class A and some child classes B1,...Bn. I would like at a point of time, having an object Bx of type A, to be able to say: this is a class Bx.

My first guess is to add a enum property inside class A defining each child class type and then store this child class type when constructing the child object:

public enum typeOfChild { B1, B..., Bn };  

public class A {     
    public typeOfChild type;
}

public class B1 : A {
    public B1() 
    {
        type = typeOfChild.B1;
    }
}

// So I can retrieve it later:
B1 Foo = new B1();

// What will happen is that I don't know the type of the child:
A FooA = Foo;

// And now I would like to retrieve this type:
Console.WriteLine(FooA.type); // B1

I need this type be sent back as a JSON property.

Is there a better/proper way to retrieve the child type of this object?

2
  • 1
    GetType() already returns the runtime type of an object, as opposed to the static type of the variable you're using to reference the object. It looks like you're trying to reinvent it. Commented Feb 26, 2018 at 8:29
  • GetType() what was I was looking for, thanks! Commented Feb 26, 2018 at 8:33

1 Answer 1

2

Assuming these class definitions:

public class A {     
}

public class B : A {
}

You can find out the type of the variable (compile time detectable) and the type of the instance (runtime only):

A a = null;

if(/*user input*/)
{   
   a = new A();
}
else
{
   b = new B();
}

// this results in A, because that's the variable type
typeof(a); 

// this results in either A or B depending on how he "if" went,
// because that's the actual type of the instance
a.GetType(); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.