Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Method inside generic class with additional constraints to T

Tags:

c#

oop

generics

I have a generic class Foo<T> where T: SomeBaseType.

And in the specific case where T is SpecificDerivedType, I want my class to have an additional method.

Something like:

class Foo<T> where T: SomeBaseType
{
    //.... lots of regular methods taking T, outputting T, etc.

    //in pseudo code
    void SpecialMethod() visible if T: SpecificDerivedType
    {
        //...code...
    }
}

How can I achieve this?

like image 821
Daniel Möller Avatar asked Dec 02 '22 11:12

Daniel Möller


2 Answers

Make an extension method for Foo<T>:

public static void SpecialMethod<T>(this Foo<T> foo)
    where T : SpecificDerivedType
{
}
like image 88
Servy Avatar answered Dec 05 '22 00:12

Servy


How can I achieve this?

You can't. Create a specialized Foo.

class SpecialFoo<T> : Foo<T> where T: SpecificDerivedType
{
    void SpecialMethod()
    {
        //...code...
    }
}

Other suggest an extension method, which is obviously not the same as what you ask. It might be a workaround though.

like image 40
Patrick Hofman Avatar answered Dec 04 '22 23:12

Patrick Hofman