1

I have a String like this:

typeStr = label1.GetType().ToString();

Now I want to reversely get the type of this control by typeStr.

I try some function like Type.GetType(typeStr) but does not help.

Is there any simple way to obtain the type?

Tuxdude
  • 47,485
  • 15
  • 109
  • 110
  • 3
    What exactly are you trying to achieve here? Why do you need a string representation of a type name and why do you need to parse it back to a `Type` object? – Oded Mar 10 '13 at 08:43
  • What exception when you tried `GetType`? – cuongle Mar 10 '13 at 08:46
  • 1
    Related or maybe dublicate http://stackoverflow.com/questions/3702916/is-there-a-typeof-inverse-operation – Soner Gönül Mar 10 '13 at 08:57
  • I want to Serislize a class whith som attributes. my class has an attribute: Type elementType, but type Type can not be serializes. I had to use type String instead of Type. – user2153384 Mar 10 '13 at 08:59
  • possible duplicate of [Convert string to Type c#](http://stackoverflow.com/questions/11107536/convert-string-to-type-c-sharp) – nawfal Dec 02 '13 at 21:14

3 Answers3

1

You can pass the Type Fullname

Type type = Type.GetType("System.Windows.Forms.Label");

This will create the type and to create the instance of object u can use Activator.CreateInstance

object obj = Activator.CreateInstance(type);



Working with Type loaded in AppDomain.CurrentDomain.GetAssemblies()

   private void btnAddDymanicLabel_Click(object sender, EventArgs e)
    {
        Type type = GetTypeNameFromDomain("System.Windows.Forms.Label");
        Label lbl = (Label) Activator.CreateInstance(type);
        this.Controls.Add(lbl);
        lbl.Text = "dynamic created control";


    }

    private Type GetTypeNameFromDomain(string typename)
    {
        return AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes().Where(type => type.FullName == typename)).FirstOrDefault();
    }

A simple example :

static void Main(string[] args)
{
    Type type = Type.GetType("System.Int32");
    object obj = Activator.CreateInstance(type);
    int num = (int) obj;
    num = 10;
    Console.WriteLine(num); // prints : 10
}
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
0

Try getting the name with

typeStr = label1.GetType().GetFullName();

Then

type = Type.GetType(typeStr);
tishu
  • 998
  • 15
  • 29
  • This is not what OP asked. He asked "is there any way to get `Type` of a string represantation of it?". And there is no `GetFullName()` method of `GetType()`. I assume you want to use `FullName` property. – Soner Gönül Mar 10 '13 at 08:47
0

Do you mean you want to get and instance of that type only from a string like this

classname instance = Activator.CreateInstance("<assemblyname>","<classname>") as classname;
user2050269
  • 81
  • 2
  • 7