-1

I have 2 classes (classA and classB) that both inherits from same class (classC). Now I need create new generic class (classAA) that inherits List of A or B. Is it possible to call methods of classC in classAA.

public class classC
{
    //...
}
public class classA : classC
{
    //...
}
public class classB : classC
{
    //...
}
public class classAA<T> : List<T>
{
    //...
}
  • 1
    Perhaps you just want `where T : classC` as a constraint in your `classAA` declaration? (As an aside, it's useful to follow naming conventions even in sample code...) – Jon Skeet Nov 05 '14 at 09:37
  • What does calling methods of `ClassC` mean for list of `ClassC`? – Konrad Kokosa Nov 05 '14 at 09:37
  • For example classC have method DrawObject(). And in classAA i want to call DrawObject() for each element in List. – user4086830 Nov 05 '14 at 09:43
  • Then you need to do what @JonSkeet said, you need to ensure that any object you pass to `classAA` is at least of type `classC` (or a descendant) by using the constraint. – Lasse V. Karlsen Nov 05 '14 at 09:54

2 Answers2

0

I believe you want something like this. Assumming:

class classC
{
    public void DrawObject() { }
}

you can put constraint on T that it will be classC or its derivatives:

class classAA<T> : List<T> where T : classC
{
    public void SomeMethod()
    {
        foreach (var item in this.Cast<classC>())
        {
            // here you can call item.DrawObject()
        }
    }
}
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
0

It's generally not a good idea to inherit from List<T>. 95% of time you should prefer composition over inheritance. See for example: Why not inherit from List<T>?

Most probably you are looking for something like:

public class classAA<T> 
    where T : ClassC
{
    public List<T> MyList { get; set; }

    public void Foo()
    {
        foreach (var item in this.MyList)
        {
            item.MethodOfClassC();
        }
    }
}
Community
  • 1
  • 1
ken2k
  • 48,145
  • 10
  • 116
  • 176