1

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
SirJosh3917
  • 309
  • 5
  • 13

2 Answers2

3

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)
{
    ...
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

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.

Mauro Sampietro
  • 2,739
  • 1
  • 24
  • 50