I’m looking through some existing code in a project I’m working on, and I found a class that is implemented as:
public class ThingOne
{
private int A;
private int B;
[NonSerialized]
private System.Timers.Timer timer1;
}
Shouldn’t it look more like this?
[Serializable]
public class ThingOne
{
private int A;
private int B;
[NonSerialized]
private System.Timers.Timer timer1;
}
Or is there some additional benefit to adding [NonSerialized] even when the class itself is not Serializable?
NonSerialized will have no effect when Serializable is not used. By default, classes and their members are non-serializable.
The only advantage of declaring something NonSerialized when the class isn’t serialized is under the circumstances that the class is inherited by a Serialized object, and then the inherited member will be non-serializable.
From MSDN: