tags:

views:

81

answers:

2

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.

A: 

Why do you even need the cast in the first place? Perhaps you want:

public void myMethod<T>(myClass<T> caller)

Otherwise, the answer to your question is - you cannot, because you do not know which particular specialization of myClass called you.

Pavel Minaev
Good point, but in public void myMethod<T>(myClass<T> caller)the T is still not valid.
Matt
Er, why? The declaration introduces a new generic type parameter. Are you sure you didn't miss `<T>` after `myMethod`? If you didn't, and it still doesn't compile, then what is the error message?
Pavel Minaev
+3  A: 

You can do this with as, as follows:

public void MyMethod(object caller)
{
    myClass<T> test = caller as myClass<T>;
    if (test != null)
    {
         // Use test here
    }
}

That being said, if you are always passing in a known myClass<T> it'd probably be cleaner to just use:

public void MyMethod(myClass<T> caller)
{
     // Use caller directly...
}


Edit: To demonstrate, here's a small sample:

using System;

public class myClass<T> where T : new()
{
    public T Value;

    public void CopyFromSecond(object caller)
    {
        myClass<T> test = caller as myClass<T>;
        this.Value = test.Value;
    }
}
class Program
{
    static void Main(string[] args)
    {
        myClass<int> test = new myClass<int> { Value = 3 };
        myClass<int> test2 = new myClass<int> { Value = 5 };

        Console.WriteLine(test.Value);
        test.CopyFromSecond(test2);
        Console.WriteLine(test.Value);
        Console.ReadKey();
    }
}

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.

Reed Copsey
If use the 'as' , I still get an error stating the T from myClass<T> is undefined
Matt
His problem is that he's doing it from _another_ class, method of which is called by some `myClass<T>`. And he wants to find out that `T`.
Pavel Minaev
@Pavel: I'm not 100% sure what he wants - but I added sample code, plus linked to the Type method required to get the typeof T. If you're correct in his desires, reflection is the only way to go.
Reed Copsey