Sys
Sys

Reputation: 413

.Net - serialize objects

If i have objects with properties of type object or objects that are generics, how can i serialize this?

Eg.

public class MyClass
{
   public Object Item { get; set; }
}

or

public class MyClass<T>
{
   public T Item { get; set; }
}

EDIT

My Generic class now looks like this:

public class MyClass<T>
{
   public MySubClass<T> SubClass { get; set; }
}

public class MySubClass<T>
{
   public T Item { get; set; }
}

Additonal question: How can i change the element name for Item at runtime to typeof(T).Name?

Upvotes: 1

Views: 635

Answers (2)

Dennis Traub
Dennis Traub

Reputation: 51694

Have you tried the [Serializable] attribute?

[Serializable]
public class MySerializableClass
{
   public object Item { get; set; }
}

[Serializable]
public class MySerializableGenericClass<T>
{
   public T Item { get; set; }
}

Although the generic class is only serializable if the generic type parameter is serializable as well.

Afaik there is no way to constrain the type parameter to be serializable. But you can check at runtime using a static constructor:

[Serializable]
public class MySerializableGenericClass<T>
{
   public T Item { get; set; }

   static MySerializableGenericClass()   
   {
      ConstrainType(typeof(T));
   }

   static void ConstrainType(Type type)
   {
      if(!type.IsSerializable)
         throw new InvalidOperationException("Provided type is not serializable");
   }
}

Upvotes: 6

Iain Ward
Iain Ward

Reputation: 9946

Use these methods to serialize\deserialize any object (even generics) to an XML file, though can be modified to suit other purposes:

public static bool SerializeTo<T>(T obj, string path)
{
    XmlSerializer xs = new XmlSerializer(obj.GetType());
    using (TextWriter writer = new StreamWriter(path, false))
    {
        xs.Serialize(writer, obj);
    }
    return true;
}

public static T DeserializeFrom<T>(string path)
{
    XmlSerializer xs = new XmlSerializer(typeof(T));
    using (TextReader reader = new System.IO.StreamReader(path))
    {
        return (T)xs.Deserialize(reader);
    }
}

Upvotes: 1

Related Questions