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 { }
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.
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? 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.
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.
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>() { }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With