views:

7022

answers:

4

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 class.

+5  A: 

Why serialise the Type? If the deserialisation is not .Net it can't use it, if it is then all you need to pass is the fully qualified name.

Keith
+1  A: 

Just looked at its definition, it is not marked as Serializable. If you really need this data to be serialize, then you may have to convert it to a custom class that is marked as such.

public abstract class Type : System.Reflection.MemberInfo
    Member of System

Summary:
Represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.

Attributes:
[System.Runtime.InteropServices.ClassInterfaceAttribute(0),
System.Runtime.InteropServices.ComDefaultInterfaceAttribute(System.Runtime.InteropServices._Type),
System.Runtime.InteropServices.ComVisibleAttribute(true)]
AdamSane
+1  A: 

According to the MSDN documentation of System.Type [1] you should be able to serialize the System.Type object. However, as the error is explicitly referring to System.Text.StringBuilder, that is likely the class that is causing the serialization error.

[1] Type Class (System) - http://msdn.microsoft.com/en-us/library/system.type.aspx

Rob
+15  A: 

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.

Brian Sullivan
Be warned that Type.GetType(typeName); will only work for types in the same assembly as the call.
GreyCloud
the solution is to use AssemblyQualifiedName instead of just FullName
GreyCloud