Tech Off Thread

4 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Best way to get a Type from a String?

Back to Forum: Tech Off
  • User profile image
    phreaks

    Anyone got a slick way of obtaining a Type from a String?

    I usually create a dictionary, Key[String], Value[Type], and then work off the dictionary to obtain the Type from the String, there has to be a better way.

    For Example, I have a list of Components somewhere (DB, Config, wherever). Some method returns me the String value of the type "MyTypes.MyControlType", now I want to turn that string into the actual Type (not an instance, just the Type).

    Ideas?

  • User profile image
    Minh

    Type.GetType(typeName) ?

  • User profile image
    phreaks

    Minh wrote:
    Type.GetType(typeName) ?


    Wow, now don't I feel silly.

    Thanks.

  • User profile image
    littleguru

    Sometimes the easiest way is so far away Smiley

    Type.GetType(...) has several nice overloads. The default overload (with one argument) returns null if the type couldn't be constructed. Sometimes the Type.AssemblyQualifiedName is required (in a string representation) to create a type from a string.

    You could also use another overload and let the method throw an exception when the type couldn't be fetched from the string.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.