0

Browsing .NET Reference source for some details on ClaimsIdentity class I noticed this:

[NonSerialized]
const string PreFix = "System.Security.ClaimsIdentity.";
[NonSerialized]
const string ActorKey = PreFix + "actor"; 

What might be a possible reason to use NonSerializedAttribute on a const?

UserControl
  • 14,766
  • 20
  • 100
  • 187
  • It needs not be serialised because its value cannot change. – Sweeper May 21 '18 at 06:35
  • const values are serializable unless they have the NonSerializedAttribute attached to them. Whoever wrote that code, decided they didn't want have those values serialized. – jwdonahue May 21 '18 at 06:38
  • Well, formally `const` is a field so `NonSerialized` is perfectly acceptable based on its description. But what's the practical benefit of this? What serializer would put consts into a stream by default? – UserControl May 21 '18 at 06:39
  • 2
    Both `SoapFormatter` and `BinaryFormatter` don't format `static` fields (and `const` is internally something like `static`) – xanatos May 21 '18 at 06:49
  • The writers of SoapFormatter and BinaryFormatter may have decided not to fields with certain attributes, such as static, but that's not the default language behavior. – jwdonahue May 21 '18 at 17:44
  • Note that the OP did not specify which formatter is in use for the posted code context. – jwdonahue May 21 '18 at 17:46

2 Answers2

0

const values are serializable unless they have the NonSerializedAttribute attached to them. Whoever wrote that code, decided they didn't want to have those values serialized.

Read the MSDN docs on the SerializableAttribute, specifically:

When you apply the SerializableAttribute attribute to a type, all private and public fields are serialized by default. You can control serialization more granularly by implementing the ISerializable interface to override the serialization process.

jwdonahue
  • 6,199
  • 2
  • 21
  • 43
0

Const are for whole class and not tied with instance.

Mahesh Malpani
  • 1,782
  • 16
  • 27