1

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?

2 Answers 2

6

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");
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I want to change the element name of MySerializableGenericClass<T>.Item to type.name of T. How can do that?
Was my answer helpful? You can tell by marking (accepting) it. Then I'll be happy to discuss your second question.
1

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);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.