Vicky

Vicky

  • NA
  • 6
  • 0

How to pass a type from DLL into generic method?

Jan 31 2008 3:26 PM
Hi,
I am trying to get my first generic method work. Here is what I want to do:
Based on diffent type of users, we need to use different DLL. The DLL is COM object wrapper, which expose a function that can be called. The original code looks like the following:

using System.Runtime.InteropServices;
using AsynchWrapper1;
using AsynchWrapper2;
using AsynchWrapper3;
....
namespace MyNameSpace
{
    public class Unility
    {
        public static void CallAsynchWrapper(int clientType,  int clientId)
        {
             if (clientType ==0)
             {
           clsAsynchWrapper1 asynchWrapper = new clsAsynchWrapper1(); 

           asynchWrapper.XYZ(clientId);

           Marshal.ReleaseComObject(asynchWrapper);

           asynchWrapper = null;

       }
       else if (clientType ==1)
       {
           clsAsynchWrapper2 asynchWrapper = new clsAsynchWrapper2(); 

           asynchWrapper.XYZ(clientId);

           Marshal.ReleaseComObject(asynchWrapper);

           asynchWrapper = null;

    }
    else 
    {

           clsAsynchWrapper3 asynchWrapper = new clsAsynchWrapper3(); 

           asynchWrapper.XYZ(clientId);

           Marshal.ReleaseComObject(asynchWrapper);

           asynchWrapper = null;

    }
  }

}
Where XYZ is the function that all 3 dlld expose. 
 
I want to make a generic method by modifying the CallAsynchWrapper function doing the following:

        public static void CallAsynchWrapper(int clientType,  int clientId)
        {
             if (clientType ==0)
             {
           clsAsynchWrapper1 asynchWrapper = new clsAsynchWrapper1(); 

           genericCallAsynchWrapper<clsAsynchWrapper1>(asynchWrapper, clientId);      

             }
       else if (clientType ==1)
       {
           clsAsynchWrapper2 asynchWrapper = new clsAsynchWrapper2(); 

           genericCallAsynchWrapper<clsAsynchWrapper2>(asynchWrapper, clientId);      

    }
    else 
    {

           clsAsynchWrapper3 asynchWrapper = new clsAsynchWrapper3(); 

           genericCallAsynchWrapper<clsAsynchWrapper3>(asynchWrapper, clientId);      

    }
   }


and add a generic method:

static void genericCallAsynchWrapper<T>(T asynchWrapper, int clientId)

        {

            asynchWrapper.XYZ(clientId);

            Marshal.ReleaseComObject(asynchWrapper);

            asynchWrapper = default(T);

        }
 
When I compile it, I got error message” T doesn’t have a definition of XYZ.”
My first question is: Is that possible to make a generic method for what I am trying to do?
If that’s possible, how can I make compiler knows that T does have XYZ?
Does anybody know the answer?

Thanks in advance for any help!

Answers (5)