user99322
user99322

Reputation: 1207

How do I get the user defined object type given the class name?

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);

Upvotes: 1

Views: 2166

Answers (2)

thecoop
thecoop

Reputation: 46108

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();
        }
    }
}

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062905

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();
    }
}

Upvotes: 6

Related Questions