Cast object for a generic method

This generates an error saying that I cannot convert the ClassType type to T Is there a workaround for this?

Is it possible to indicate that this type can actually be converted to T ?

 public void WorkWith<T>(Action<T> method) { method.Invoke((T)this); } 
+6
source share
2 answers

Two possible solutions:

Unsafe

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

This is not typical because you can pass it any method that has a single parameter and does not return a value, for example:

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

Typical "version" (using common restrictions):

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

The thing is, in order to be able to discard this in T , the compiler wants to make sure that this always applies to T (so the need for a constraint). As shown in the example of an unsafe type, the "classic" (unsafe) solution used with generics goes through the listing to object .

+3
source
 public void WorkWith<T>(Action<T> method) where T: ClassType { method.Invoke((T)this); } 
+3
source

All Articles