Reputation: 744
I'm recently learning C# serialization myself. I noticed the [NonSerializable]
Attribute and wonderd why it should/could/must be used and what the reasons for that could be.
Here are some of my research sites I used:
MSDN article about the NonSerializable attribute (contains an example but no reason why it should/shouldn't be used)
Are there examples which seriously can't be serialized (theoretical and practical)?
Why should/n't it be used?
Upvotes: 0
Views: 1287
Reputation: 3417
I can think of a few reasons why not to serialize some fields, for example when:
Upvotes: 2
Reputation: 4135
If I utilize attributes to prevent serialization, it's typically because I want to secure data, or it because it wouldn't make sense to serialize a given field (maybe one that isn't itself serializable, or something that gets initialized every time the class is instantiated).
For example, say I had a record I wanted to save that is associated with a user. I may want to save their name, but never their password:
[Serializable]
public struct User
{
public string Name;
//this should never be persisted
[NonSerialized]
public string Password;
}
//when I persist this, it persists the CreatedBy User without the password
[Serializable]
public class Record
{
//password won't be persisted now
public User CreatedBy{ get; set; }
//other information I want to save
}
Other times, I may have a non-serializable property that I don't want saved or sent across the wire after serialization.
[Serializable]
public class Whatever
{
public Whatever()
{
//this always gets new-ed up, so there's no point in persisting it.
//maybe it's not even serializable!
HelperUtility = InitHelper();
}
//no sense in serializing this helper utility
[NonSerialized]
public NonSerializableClass HelperUtility;
//but I may want to actually save this!
public string DataIActuallyWantToSave;
}
That's the gist.
Such attributes do actually see use in the real world, and I've used them many times.
Upvotes: 2