Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing objects in C# 4.0, is there a simpler way?

When set up an object for serialization I do the following:

[Serializable]
public class ContentModel
{
    public int ContentId { get; set; }
    public string HeaderRendered { get; set; }

    public ContentModel()
    {
        ContentId = 0;
        HeaderRendered = string.Empty;
    }

    public ContentModel(SerializationInfo info, StreamingContext ctxt) 
    {
        ContentId = (int)info.GetValue("ContentId", typeof(int));
        HeaderRendered = (string)info.GetValue("HeaderRendered", typeof(string));
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("ContentId ", ContentId);
        info.AddValue("HeaderRendered", HeaderRendered);
    }
}

It's quite exhausting when there are lots of properties. Is there a simpler or less verbose way of doing this in C# 4.0?

like image 513
craigmoliver Avatar asked Dec 10 '25 22:12

craigmoliver


2 Answers

You don't need the extra constructor or the GetObjectData method unless you want to customize the serialization mechanism. If you have simple properties, the default serialization mechanism will handle them quite well. All you need is the Serializable attribute, and you're golden.

like image 185
Nader Shirazie Avatar answered Dec 12 '25 10:12

Nader Shirazie


Why are you doing this by hand? BinaryFormatter already knows how to do this automatically. If filtering the fields is important then make another class that just stores the ones that you want to serialize.

like image 42
Hans Passant Avatar answered Dec 12 '25 10:12

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!