leAthlon
leAthlon

Reputation: 744

Why and when should the NonSerializable Attribute used?

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:


Actual questions:

Upvotes: 0

Views: 1287

Answers (2)

Dzienny
Dzienny

Reputation: 3417

I can think of a few reasons why not to serialize some fields, for example when:

    - they contain an unencrypted vulnerable data like a password, pin etc.,
    - they are used to store uncompressed data (eg bitmap) and there's a field containing the compressed equivalent available,
    - they are created in the object constructor (eg timer).

Upvotes: 2

Colin
Colin

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

Related Questions