Adding more control by implementing ISerializable

suggest change

Implementing ISerializable gives more control over how a type is saved and loaded.

Implement ISerializable and add a constructor that takes SerializationInfo and StreamingContext. That constructor is not part of the interface, but the formatter calls it during deserialization. An empty public constructor is not required for the type to compile.

[Serializable]
public class Item : ISerializable
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public Item ()
    {

    }

    protected Item (SerializationInfo info, StreamingContext context)
    {
        _name = (string)info.GetValue("_name", typeof(string));
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("_name", _name, typeof(string));
    }
}

For data serialization, you can specify the desired name and the desired type

info.AddValue("_name", _name, typeof(string));

When the data is deserialized, you will be able to read the desired type

_name = (string)info.GetValue("_name", typeof(string));

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents