Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast object to method generic type

Tags:

c#

generics

This generates an error saying I cannot convert type ClassType to T. Is there any workaround for this?

Is there any way to specify that the type of this can in fact be converted to T?

public void WorkWith<T>(Action<T> method)
{
    method.Invoke((T)this);
}
like image 725
KthProg Avatar asked Feb 25 '16 14:02

KthProg


1 Answers

Two possible solutions:

Not type-safe:

public void WorkWith<T>(Action<T> method)
{
    method.Invoke((T)(object)this);
}

This isn't typesafe because you can pass it any method that has a single parameter and no return value, like:

WorkWith((string x) => Console.WriteLine(x));

The typesafe "version" (using generic constraints):

public class MyClass
{
    public void WorkWith<T>(Action<T> method) where T : MyClass
    {
        method.Invoke((T)this);
    }
}

The point here is that to be able to cast this to T, the compiler wants to be sure that this is always castable to T (so the need for the constraint). As shown in the not-type-safe example, the "classical" (unsafe) solution used with generics is passing through a cast to object.

like image 163
xanatos Avatar answered Sep 30 '22 18:09

xanatos