Joe Martiniello Joe Martiniello - 1 month ago 13
C# Question

Assign to Readonly Property

Hello i want to serialize an object but,
if try to deseriliaze a IEnumerable<> i get this error

Error 75 Property or indexer 'Nodes' cannot be assigned to -- it is read only

My example code:

Serializing Part.

FileStream fs = new FileStream(sv.FileName, FileMode.Create, FileAccess.ReadWrite);
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(fs, graphControl.Nodes);
fs.Close();


Deserializing Part:

FileStream fs = new FileStream(op.FileName, FileMode.Open, FileAccess.ReadWrite);
BinaryFormatter bin = new BinaryFormatter();

//Error Here

graphControl.Nodes = (IEnumerable<Node>)bin.Deserialize(fs);


Node Class Part:

public List<Node> graphNodes = new List<Node>();
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public IEnumerable<Node> Nodes { get { return graphNodes; } }


Anyone can help me?

Answer

graphNodes shouldn't be public, but since it is, use it:

graphControl.graphNodes = (IEnumerable<Node>)bin.Deserialize(fs);

But it really shouldn't be public, so this is better:

graphControl.Nodes.Clear();
graphControl.Nodes.AddRange( (IEnumerable<Node>)bin.Deserialize(fs) );

...and make graphNodes private.

Comments