Daniel Möller
Daniel Möller

Reputation: 86600

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

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?

Upvotes: 5

Views: 372

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1500245

There's nothing quite like that, but you could add an extension method on Foo<T> with a more specific constraint than T normally has. Here's a complete example:

using System;

class SomeBaseType {}
class SomeDerivedType : SomeBaseType {}

static class FooExtensions
{
    public static void Extra<T>(this Foo<T> foo)
        where T : SomeDerivedType
    {
        Console.WriteLine("You have extra functionality!");
    }
}

class Foo<T> where T : SomeBaseType
{
}

class Program
{
    static void Main(string[] args)        
    {
        Foo<SomeBaseType> foo1 = new Foo<SomeBaseType>();
        Foo<SomeDerivedType> foo2 = new Foo<SomeDerivedType>();

        // Doesn't compile: the constraint isn't met
        // foo1.Extra();

        // Does compile
        foo2.Extra();
    }
}

That allows you to call the method on an existing instance rather than having to create a more specialized instance. On the other hand, it relies on the extension method having enough access to do whatever it needs to in Foo<T>. You may need to have an unconstrained internal method in Foo<T> for FooExtensions.Extra to call.

Upvotes: 4

Servy
Servy

Reputation: 203821

Make an extension method for Foo<T>:

public static void SpecialMethod<T>(this Foo<T> foo)
    where T : SpecificDerivedType
{
}

Upvotes: 7

Patrick Hofman
Patrick Hofman

Reputation: 156958

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.

Upvotes: 4

Zazaeil
Zazaeil

Reputation: 4119

You can create an extension method that will look like this:

public static void SpecificMethod<T>(this Generic<T> instance) 
    where T : SpecificDerivedType

Upvotes: 2

Related Questions