Home > Software engineering >  C# Generic Method from Base Class
C# Generic Method from Base Class

Time:09-24

I have the following scenario:

public abstract class AAA<T> where T : BBB<T>
{
}

public abstract class BBB<T> : AAA<T> where T : BBB<T>
{
    public void SomeMethod() { }
}

public class CCC : BBB<CCC>
{
}

And they are in turn used with the following.

public class YYY
{
    public void Bar(BBB bbb, int value)
    {
        bbb.SomeMethod();
    }
}

public class ZZZ : YYY
{
    public void Foo()
    {
        CCC instance = new CCC();
        Bar(instance, 0);
    }
}

How do I structure the declaration of YYY.Bar() for parameter bbb so that it can accept an argument of type CCC? Class ZZZ knows about type CCC, but class YYY only has knowledge of AAA and BBB. This is common practice in other languages, e.g. Java, but I can't seem to make it work in C#.

CodePudding user response:

You need to make your method Bar generic:

public class YYY
{
    public void Bar<T>(BBB<T> bbb, int value) where T : BBB<T>
    {
        bbb.SomeMethod();
    }
}

Another option is to make YYY generic itself, not sure if it is suitable in your scenario though:

public class YYY<T> where T : BBB<T>
{
    public void Bar(BBB<T> bbb, int value)
    {
        bbb.SomeMethod();
    }
}

public class ZZZ : YYY<CCC>
{
    public void Foo()
    {
        CCC instance = new CCC();
        Bar(instance, 0);
    }
}
  • Related