Arturo Hernandez
Arturo Hernandez

Reputation: 2859

Can I call an extension method from inside a generic class?

Is there a way to call an extension from within a generic class, where the variable class is also the extended class? Here is a sample piece of code. It does not compile.

public class GenericFoo<TFrom,TTo>
{
   public TTo GenericFoo(TFrom A)
   {
      return A.Bar();
   }
}

public static class Extensions
{
    public static MyType Bar(this MyExtendedType source)
    {
       return new MyType();
    }
}

This produces the following error:

'TFrom' does not contain a definition for 'Bar' and the best extension method overload 'MyNamespace.Extensions.Bar(MyNamespace.MyExtendedType)' has some invalid arguments

Upvotes: 3

Views: 152

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 148980

You can if you add a generic type constraint:

public class GenericFoo<TFrom, TTo>
    where TFrom : MyExtendedType
    where TTo : MyType
{
   public TTo SomeMethod(TFrom A)
   {
      return (TTo)A.Bar();
   }
}

This will be enough to get it to compile, though you will still get a run-time error if no cast exists from MyType to TTo.

Further Reading

Upvotes: 2

Related Questions