4

I need to make a class Serializable. In this class I have a MyGuid readonly property, that I want to be serializable but not deserializable (property is initialized in a backing field). Using base serialization .NET features, you know, have a reandonly property make deserialization fail, 'cause it cannot deserialize a readonly property. So I decide to create a public get-set MyGuid property with a backing field, and make setter do nothing:

[Serializable]
public class Task : ITask
{
    private readonly Guid m_guid = Guid.NewGuid();
    public MyGuid Guid
    {
        get { return m_guid; }
        set { /*Empty setter!*/ }
    }
}

Now I don't want to shoot in my foot... There's a way I can make setter of MyGuid property as "deprecable" or "disabled"? It would be nice have Visual Studio warning me if I try to use the setter.

Or, instead, there's a better way to manage this kind of needs?

Thank you!

Edit: Found something here: Serializing private member data I'm reading...

Community
  • 1
  • 1
Ferdinando Santacroce
  • 935
  • 3
  • 11
  • 30
  • If you're not going to ever deserialise it, why serialise it? Could you use the `[NonSerialized]` or `System.Xml.Serialization.XmlIgnore]` attributes on the property? – George Duckett May 26 '11 at 10:31

2 Answers2

2
public Guid Guid
{
    get { return m_guid; }
    set { if (value != null) Debugger.Log(0, "Warning", "This property has an empty setter, just for serializing purpose!"); }
}

This if you accidentally set the value yourself, you'll get a warning in the debug window. On the other hand, you absolutely need the setter for the serializer, or otherwise the deserializer would never be able to appoint the property a value after reading it from the file! So the setter is not for you but for the serializer to function normally.

Ferdinando Santacroce
  • 935
  • 3
  • 11
  • 30
Teoman Soygul
  • 24,721
  • 6
  • 63
  • 78
0

If you dont include the set, it will auto know its read only, so wont let you set it. It would then flag errors in your code when you try

BugFinder
  • 16,027
  • 4
  • 35
  • 49