Let’s say that I have this:
public abstract class myClass<T> : Ob<T> where T : Ob<T>, new()
Now in a method defined inside abstract myClass, I create an object of class myType and on a method defined inside myType, I pass the abstract class myClass calling it.
So in my myType class, I have:
public void myMethod(object caller)
My question is, how do I cast object caller to the type of the abstract class that called it?
I tried
(myClass<T>)
and
(myClass)
but both failed.
Generics make my head hurt.
You can do this with as, as follows:
That being said, if you are always passing in a known
myClass<T>it’d probably be cleaner to just use:Edit: To demonstrate, here’s a small sample:
This prints 3 then 5, as expected.
Edit 2:
If you’re trying to find the type of T from another
myClass<T>, you’ll need to use reflection. The method you need is Type.GetGenericTypeDefinition.