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?
In case the class refers to non-serializable objects and these objects should not be serialized, then, you can declare these objects as transient. Once a field of a class is declared as transient, then, it is ignored by the serializable runtime.
It is not necessary to use this attribute if a given type implements the System. Runtime. Serialization. ISerializable interface, which indicates that a class provides its own methods for serialization.
Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions such as: Sending the object to a remote application by using a web service.
In C#, serialization is the process of converting object into byte stream so that it can be saved to memory, file or database. The reverse process of serialization is called deserialization. Serialization is internally used in remote applications.
Or is there some additional benefit to adding [NonSerialized] even when the class itself is not Serializable?
The class isn't sealed, so another class could inherit from that object. That class could be marked as Serializable, and then the NotSerializable attribute would come into play. (although as pointed out not for private members).
Remember you can check attributes by reflection too. It may not be used by the runtime to check what should and should not be serialized, it could be used as a marker for something else in the program dealing with some sort of custom serialization (I'm not saying this is a good idea in the least).
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:
'NonSerialized' attribute will not affect this member because its containing class is not exposed as 'Serializable'.
By default, classes and their members are non-serializable. The NonSerializedAttribute attribute is only needed if a member of a serializable class should not be serialized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With