How to Ignore a property from being serialized using BinaryFormatter?
binaryformatter, c#, serialization
Solution
You don't have to make any changes to your code: `BinaryFormatter` only serializes fields, not properties, so it won't serialize `Value`.
Here's a hex dump of the resulting `MemoryStream` which shows that only "_name" and "Ho" are serialized:
00 01 00 00 00 FF FF FF FF 01 00 00 00 00 00 00 .....ÿÿÿÿ.......
00 0C 02 00 00 00 3B 44 65 6D 6F 2C 20 56 65 72 ......;Demo, Ver
73 69 6F 6E 3D 31 2E 30 2E 30 2E 30 2C 20 43 75 sion=1.0.0.0, Cu
6C 74 75 72 65 3D 6E 65 75 74 72 61 6C 2C 20 50 lture=neutral, P
75 62 6C 69 63 4B 65 79 54 6F 6B 65 6E 3D 6E 75 ublicKeyToken=nu
6C 6C 05 01 00 00 00 0B 44 65 6D 6F 2E 44 4F 54 ll......Demo.DOT
68 69 73 01 00 00 00 05 5F 6E 61 6D 65 01 02 00 his....._name...
00 00 06 03 00 00 00 02 48 6F 0B ........Ho.
Problem
``` [Serializable] class DOThis { private string _name; public string Name { get { return _name; } set { _name = value; } } public string Value { get { if (_name == "Hi") return "Hey Hi"; else return "Sorry I dont know you"; } } } ``` I have the above class to be serialized using BinaryFormatter. Below is the serialization code, ``` DOThis obj = new DOThis(); obj.Name = "Ho"; BinaryFormatter bfm = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bfm.Serialize(ms, obj); ``` Here how to ignore the property 'Value' from being serialized and also in deserialize, as I can always retrieve 'Value' property using 'Name' property?