Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra generic parameter in generic extension methods?

I would like make an extension method for the generic class A which takes yet another generictype (in this example TC), but i guess that aint possible?

class Program
{
    static void Main(string[] args)
    {
        var a = new A<B, B>();
        a.DoIt<B>();
    }
}

static class Ext
{
    public static A<TA, TB> DoIt<TA, TB, TC>(this A<TA, TB> a)
    {
        return a;
    }
}

class A<TA, TB> { }
class B { }
like image 289
Carl Hörberg Avatar asked Feb 26 '10 22:02

Carl Hörberg


People also ask

What are extended methods in C#?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What is generic in asp net?

Generics are classes, structures, interfaces, and methods that have placeholders (type parameters) for one or more of the types that they store or use. A generic collection class might use a type parameter as a placeholder for the type of objects that it stores.

What is extension method in MVC?

What is extension method? Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.

What is generic type parameter in C#?

Parameters. The type parameter is a placeholder for a specific type that the client specifies when they create an instance of the generic type. A generic class cannot be used as-is because it is simply a blueprint for that type.


1 Answers

If you can accept a slight syntax change, then it would be possible.

Change it to:

var a = new A<B, B>(); 
a.Do().It<B>(); 

The trick is that the Do method is an extension method on A<TA, TB>:

public static Doer<TA, TB> Do<TA, TB>(this A<TA, TB> a)
{
    return new Doer<TA, TB>(a);
}

The trick is that this signature lets type inferincing pick up TA and TB from a so that you don't have to specify them explicitly.

The Doer class provides the generic method you need:

public class Doer<TA, TB>
{
    public void It<TC>() { }
}
like image 112
Mark Seemann Avatar answered Oct 13 '22 16:10

Mark Seemann