Can I serialize a C# Type object?

Question :

Can I serialize a C# Type object?,

Answer :

I’m trying to serialize a Type object in the following way:

Type myType = typeof (StringBuilder);  var serializer = new XmlSerializer(typeof(Type));  TextWriter writer = new StringWriter();  serializer.Serialize(writer, myType);  

When I do this, the call to Serialize throws the following exception:

“The type System.Text.StringBuilder was not expected. Use the
XmlInclude or SoapInclude attribute to specify types that are not
known statically.”

Is there a way for me to serialize the Type object? Note that I am not trying to serialize the StringBuilder itself, but the Type object containing the metadata about the StringBuilder clas

Read More  Why should I learn Lisp?

,

I wasn’t aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following:

string typeName = typeof (StringBuilder).FullName;  

You can then persist this string however needed, then reconstruct the type like this:

Type t = Type.GetType(typeName);  

If you need to create an instance of the type, you can do this:

object o = Activator.CreateInstance(t);  

If you check the value of o.GetType(), it will be StringBuilder, just as you would expect.

That’s the answer Can I serialize a C# Type object?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Read More  Learning Version Control, and learning it well

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you