Brad Mash
Brad Mash

Reputation: 69

C# Upcasting / Polymorphism Issue

I believe this question is fairly basic but I am having trouble finding an answer to this question. In C# let's say I have 3 classes: A, B, C

B derives from A

C derives from B

Now, if I wanted a list or array of objects of type class A but wanted the array to be able to house objects of type B and C this is no problem... I could do something like this:

A[] myArrayofAtypes;

However let's say I make the first element of this array of type C. If type C has a variable defined in its class definition that ONLY exists in class C's class definition... how do I access that variable from the array? I can't just do A[0].MyVariableGetter as that variable does not exist in the base class, A.

Any suggestions?

Upvotes: 0

Views: 234

Answers (3)

Huhra
Huhra

Reputation: 92

Instead of casting as 'king.code' has suggested like this I would use these pretty C# operators which are 'is' and 'as'.

public void CallIfTypeC(A a)
{
    if (a is C)
    {
        C c = a as C;
        c.DoAction();
    }
}

Upvotes: 0

user92454
user92454

Reputation: 1211

You have to type cast it to type c and access the member.

If (arr[i] is c)
{
    ((C)arr[0]).member = value;
 }

Upvotes: 0

dario
dario

Reputation: 5259

You have to downcast it:

C c = (C)myArrayofAtypes[0];
var v = c.MyVariableGetter;

Upvotes: 1

Related Questions