12

I have an API using generic method as follow

public static class DataProvider
{
    public static Boolean DeleteDataObject<T>(Guid uid, IDbConnection dbConnection)
    {
        // Do something here
    }

    public static IDbConnection GetConnection()
    {
        // Get connection
    }
}

My application contains classes generated using CodeDOM at runtime, and in order to keep track of I created an interface called IDataObject. I am trying to pass the concrete type of each object to the generic method above as follow:

public static Boolean PurgeDataObject(this IDataObject dataObject, Guid uid)
{
    return DataProvider.DeleteDataObject<T>(uid, DataProvider.GetConnection());
}

dataObject contains an instance of a class that inherit from IDataObject. I am interested in getting that type and pass it as T. I am trying to find out if it is possible to somehow use dynamic here. typeof() and GetType() does not work as stated in Here

Community
  • 1
  • 1
Moslem Ben Dhaou
  • 6,897
  • 8
  • 62
  • 93
  • 2
    There are some tricks to use dynamic as a bridge between reflection and generics, but they require an instance. If you don't have an instance, MakeGenericMethod is your main tool. Or a non-generic API... – Marc Gravell May 10 '13 at 22:33
  • @MarcGravell: `dataObject` is an instance which contains the Type information I am trying to extract and pass. Have a look at Jon's answer – Moslem Ben Dhaou May 10 '13 at 22:58

1 Answers1

21

I suspect you want something like this:

public static Boolean PurgeDataObject(this IDataObject dataObject, Guid uid)
{
    return PurgeDataObjectImpl((dynamic) dataObject, uid);
}

private static Boolean PurgeDataObjectImpl<T>(T dataObject, Guid uid)
    where T : IDataObject
{
    return DataProvider.DeleteDataObject<T>(uid, DataProvider.GetConnection());
}

That uses dataObject dynamically, getting the "execution-time compiler" to perform type inference to work out T.

You could just use reflection to do this yourself, using MethodInfo.MakeGenericMethod - but this way is certainly less code.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • The call in the first method should be `return PurgeDataObjectImpl((dynamic) dataObject, uid);` (wrong method name, less than 6 characters, I can't edit) – Moslem Ben Dhaou May 10 '13 at 23:02
  • +1 -this dynamic cast is perfect for a little corner case that's been baffling me for the past hour. i just hope i don't `over-use` it, in favour of thinking out the options - so increadibly simple and too the point. thanks – jim tollan Sep 01 '14 at 08:50
  • m3alim sa7bi Jon – Methnani Bilel Aug 09 '22 at 14:55