Home > OS >  Use a future subclass type in a base class method
Use a future subclass type in a base class method

Time:10-25

Say I have a base class BaseFoo and a method to do something with a data structure composed entirely of BaseFoo:

public class BaseFoo { // FWIW, in my "real" example, this is an abstract base class
    public void Func(IEnumerable<BaseFoo> data) {
        // impl.
    }
}

Then I have some sub-classes, Bar and Baz:

public class Bar : BaseFoo {}
public class Baz : BaseFoo {}

But I realize that it's very important that my argument to Func contains objects of all the same type, and that the type matches the subclass! Disaster may strike if the inherited Bar.Func method is passed new[] {new Bar(), new Baz()}.

How can I enforce this in the declaration of BaseFoo.Func? (I can't use a generic <T> where T : BaseFoo, because the compiler would just use BaseFoo for T, and the bad example at the end of the last paragraph would compile.)

Edit: Perhaps a better example: I want to store a list of Bars in my Bar subclass, and similarly for Baz. But I want to write one declaration in FooBase for List<this.GetType()>, knowing full well that won't compile. I'm just looking for a way to use an arbitrary subclass's type in the base class.

CodePudding user response:

One way is to use Generics

Example

public class BaseFoo<T> 
{
    public void Func(IEnumerable<T> data) { }
}

public class Bar : BaseFoo<Bar> {}
public class Baz : BaseFoo<Baz> {}

Which means

var bar = new Bar()
bar.Func(new List<bar>()) // can only ever take an enumerable of bar

Disclaimer : This disregards any other problem you might have conceptually or otherwise

  • Related