tags:

views:

230

answers:

2

If I have the class name of the user defined object as a string how do I use it in a generic function as Type of the object ?

SomeGenericFunction(objectID);

A: 

Look at the System.Type.GetType() methods - provide the fully qualified type name and you get the corresponding Type object back. You can then do something like this:

namespace GenericBind {
    class Program {
        static void Main(string[] args) {
            Type t = Type.GetType("GenericBind.B");

            MethodInfo genericMethod = typeof(Program).GetMethod("Method");
            MethodInfo constructedMethod = genericMethod.MakeGenericMethod(t);

            Console.WriteLine((string)constructedMethod.Invoke(null, new object[] {new B() }));
            Console.ReadKey();
        }

        public static string Method<T>(T obj) {
            return obj.ToString();
        }
    }

    public class B {
        public override string ToString() {
            return "Generic method called on " + GetType().ToString();
        }
    }
}
thecoop
private class TestClass : BaseClass { public TestClass( long id ) : base( id ) { } }
namespace main{public MyClass{private string className;private long classID;//constructor MyClass(BaseClass obj1){ className = obj1.GetType().FullName; classID = obj1.ID;}public void FindObject(){ //find from database calling function // need to pass in T in the following function given classname. FindByID<T>(classID)}}}
+5  A: 

If you have a string, then the first thing to do is to use Type.GetType(string), or (preferably) Assembly.GetType(string) to get the Type instance. From there, you need to use reflection:

Type type = someAssembly.GetType(typeName);
typeof(TypeWithTheMethod).GetMethod("SomeGenericFunction")
          .MakeGenericMethod(type).Invoke({target}, new object[] {objectID});

where {target} is the instance for instance methods, and null for static methods.

For example:

using System;
namespace SomeNamespace {
    class Foo { }
}
static class Program {
    static void Main() {
        string typeName = "SomeNamespace.Foo";
        int id = 123;
        Type type = typeof(Program).Assembly.GetType(typeName);
        object obj = typeof(Program).GetMethod("SomeGenericFunction")
            .MakeGenericMethod(type).Invoke(
                null, new object[] { id });
        Console.WriteLine(obj);
    }
    public static T SomeGenericFunction<T>(int id) where T : new() {
        Console.WriteLine("Find {0} id = {1}", typeof(T).Name, id);
        return new T();
    }
}
Marc Gravell