tags:

views:

127

answers:

1

I would have made the title more specific but I don't know how to put it. I'm trying to infer the type of a generic's generic.

public class BaseAction<T>
{
   public virtual void Commit(T t1, T t2){ //do something };
}

public class SpecificAction : BaseAction<int>
{
   // I would have specific code in here dealing with ints
   // public override void virtual Commit(int t1, int t2)
}

public static class DoSomething
{
    // this obviously doesn't compile
    // I want this method to know what K is based off of T.
    // eg. T is SpecificAction of type BaseAction<int>
    // can I get int from T ?
    public static void Execute<T>(K oldObj, K newObj) where T : BaseAction<K>, new()
    {
        T action = new T();
        action.Commit(oldObj, newObj);
    }
}

I want to be able to write something like this, with helpful intellisense. Is it possible?

DoSomething.Execute<SpecificAction>(5,4);
+2  A: 

I think the best case you can achieve is something like this:

public static class DoSomething
{
    public static void Execute<T,K>(K oldObj, K newObj) 
                                      where T : BaseAction<K>, new()
    {
        T action = new T();
        action.Commit(oldObj, newObj);
    }
}

and you'd have to specify:

DoSomething.Execute<SpecificAction, int>(5,4);

I doubt there would be a compile-time method to infer the generic parameter of a base class.

I have another idea (which I don't suggest, but for the record):

public static void Execute<T, K>(Func<T> constructor, K oldObj, K newObj) 
                            where T : BaseAction<K> // no `new()` necessary
{
    T action = constructor();
    action.Commit(oldObj, newObj);
}

which you could use with:

DoSomething.Execute(() => new SpecificAction(), 4, 5);
Mehrdad Afshari
Yeah, I was afraid of that. I had it like this originally, I may just have to go back to it.
Jab
Thanks for the help, I just went back to the first option. The second option is very neat however!
Jab