SirJosh3917
SirJosh3917

Reputation: 309

C# How to reference an inherited class from a base class

I am trying to refernce an inherited class from a base class, here's an example of what I have:

public class A
{
//Some methods Here
}
public class B : A
{
//Some More Methods
}

I also have a List<A> of which I've added B to, and I'm trying to access B from. Is there a way I can get B from the List<A> I have?

Upvotes: 1

Views: 4303

Answers (2)

Mauro Sampietro
Mauro Sampietro

Reputation: 2814

You could add a property of type A and provide a constructor to assign it. You can then assing an instance of type B to that property.

public class A
{
      public A Child{ get; private set; }

      public A(){}

      public A( A child )
      { 
          this.Child = child;
      }
}

Anyway.. are you really sure that strong parent/child relation is really needed? I think you could avoid it and make everything clearer, but you should provide your real world example (or something closer to you real world usage) in order to help.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

If you have added B instances to List<A> you could cast back the item to B:

List<A> items = ...
foreach (A item in items)
{
    // Check if the current item is an instance of B
    B b = item as B;
    if (b != null)
    {
        // The current item is instance of B and you can use its members here
        ...
    }
}

Alternatively you could use the OfType<T> extension method in order to get a subset of all items in the list which are instances of B:

List<A> items = ...
List<B> bItems = items.OfType<B>().ToList();
foreach (B item in bItems)
{
    ...
}

Upvotes: 3

Related Questions