0

How can I convert my Class1 or class of object to a String and then convert the String back to a type that I can use for instantiation ?

Something like that:

// class to string:
Type type1 = myObject.GetType();
string text = type1.ToString();

// and then back
Type type2 = Type.Parse(text);
// type2 should reflect the same type as type1

To do that with enums is really easy and nice. So I would like to have that with classes. I also want to avoid using serialization and XML. I don't want to serialize objects but JUST to remember the class I need to instantiate for an object.

Bitterblue
  • 13,162
  • 17
  • 86
  • 124
  • why would you want to do that in the first place? – wterbeek Jun 04 '13 at 07:10
  • So your goal is to save the CLASS name to a string and not serialize or persist the data in the instanced class? :S – Patrick Magee Jun 04 '13 at 07:11
  • do you mean just remember the name of the class? myClassInstance.GetType().FullName – Fredrik Jun 04 '13 at 07:15
  • possible duplicate of [How to dynamically create generic C# object using reflection?](http://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-c-sharp-object-using-reflection) – huysentruitw Jun 04 '13 at 07:17
  • Right, every question is a duplicate to "What is the answer to the Ultimate Question of Life, The Universe, and Everything ?" – Bitterblue Jun 04 '13 at 07:50

2 Answers2

4

If serialization is not needed, the Activator.CreateInstance method can be useful. There are a number of overloads - some work directly with strings (representing Types), and others with Type objects.

Of course, it might be convenient (or more extensible) to use a serializer that also stores the Type information.

user2246674
  • 7,621
  • 25
  • 28
  • Another possibility could be to just remember the Type object. Why the round-trip to a string? – Myrtle Jun 04 '13 at 07:15
2

If it is just the Type you want, then:

Type type = ...
string s = type.AssemblyQualifiedName; // and store s
Type andBackAgain = Type.GetType(s);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900