Creating a generic method and using a type parameter

I created this method, which is a factory object:

public static T GetService<T>(T serviceInterface) { if (serviceInterface.Equals(typeof(IMemberService))) { return (T)(object)new MemberService(); } else if (serviceInterface.Equals(typeof(ILookupService))) { return (T)(object)new LookupService(); } throw new ArgumentOutOfRangeException("No action is defined for service interface " + serviceInterface.Name); } 

Now I would like to go further and eliminate the need for the "serviceInterface" parameter, but my problem is I do not know how to compare a parameter of type T with an interface: do

 T.Equals(typeof(ILookupService)) 

gives a compiler error: "T" is a "type parameter" that is not valid in this context.

Any ideas how I can compare the type parameter with the interface?

Thanks Andrew

+7
generics c # interface
source share
4 answers

You can use typeof(T) to get a Type object that can replace using serviceInterface

for example

 public static T GetService<T>() { Type serviceInterface = typeof(T); if (serviceInterface.Equals(typeof(IMemberService))) { return (T)(object)new MemberService(); } else if (serviceInterface.Equals(typeof(ILookupService))) { return (T)(object)new LookupService(); } throw new ArgumentOutOfRangeException("No action is defined for service interface " + serviceInterface.Name); } 
+7
source share

Use typeof(T) .

So,

 typeof(T).Equals(typeof(ILookupService)) 
+1
source share
 if (typeof(IMemberService).IsAssignableFrom(typeof(T))) {} else if (typeof(ILookupService).IsAssignableFrom(typeof(T))) {} 
+1
source share

Can an operator be used?

0
source share

All Articles