0

I have a class name as a string. I can then use the following to create a new instance

var assemblyName = Assembly.GetExecutingAssemble().FullName;
var myObj = Activator.CreateInstance(assName, myClassName);

My issue is that I have the following generic method declaration

public static async Task myMethod<T>(string id) where T:IIdentity //boxing

I cannot call this method via

myMethod<myObj>("hello");

as myObj isn't of type T.

Is there a way that I can create a valid instance of myClassName that can be passed to my generic method?

Nodoid
  • 1,449
  • 3
  • 24
  • 42
  • 1
    you can use mentioned link http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method – Dhaval Patel May 19 '14 at 05:16
  • 4
    Nowadays, disk-space is cheap, and compilers are fast. Suggestion: use fully descriptive names for your variables. Like, say *assembly*Name, rather than *ass*Name :) – dlev May 19 '14 at 05:17

1 Answers1

0

Try this

public static async Task myMethod<T>(string id, T ident) where T:IIdentity

Call this using

myMethod<IIdentity>("hello", myObj);

Let me know if this helps. You might need to fix the method body of myMethod. If you can't fix it you can edit your post to add the method body and I will edit my post to show you the fix. Cheers!!!

phoenixinobi
  • 144
  • 1
  • 8
  • My only issue is now getting the instance of the object. If I use var domain = AppDomain.CurrentDomain; var name = "mynamespace.here"; var myObj = Activator.CreateInstance(domain,name,type); causes the code to crash – Nodoid May 19 '14 at 06:45
  • Ok, I've got assemblyName = Assembly.GetExecutingAssembly().FullName; var name = "myClass.Here."; var myObj = Activator.CreateInstance(assemblyName, name + type); var myObjT = myObj.GetType(); this is fine. If I then try as you've suggested, I get the error "The type 'system.type' cannot be used as a parameter 'T' in the generic type of method 'MyCode.GetData(string,T). There is no implicit cast from system.type to IIdentity' – Nodoid May 19 '14 at 07:06
  • Oh I see. The way you are using generics will not work. Generics T is resolved at compile time, so there is no way for the compiler to know that the type from your myObj.GetType(). You have to find other ways to do what you want to do other than using Generics. – phoenixinobi May 19 '14 at 07:40