Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Using Class don't Support Serializable

Everyone:

I viewed a way of avoiding some using class don't support serializable. But I don't know the reason of using this method. So I posed the question here.

So the previous code likes following

    [Serializable]
    Class OutterClass
    {
        public UsingClass UsingClassMember
        {
            get;
            set;
        }
    }

So here, if I want to serialize the OutterClass, it will occur a exception because the UsingClass don't support serializing. Obviously, all the members in the OutterClass should support serializing if I want to serialize the OutterClass.

But if I modify the code as following. The serialize operation can be done successfully.

    [Serializable]
    Class OutterClass
    {
        [NonSerialized]
        private UsingClass m_UsingClassMember;
        public UsingClass UsingClassMember
        {
            get { return m_UsingClassMember; };
            set { m_UsingClassMember = value };
        }
    }

I don't know the reason of this modification. It seems that property UsingClassMember's serialization don't need to serialize the class UsingClass itself. Can anyone give me a explanation?

Thanks!

like image 557
newcarcrazy Avatar asked Jun 16 '26 16:06

newcarcrazy


2 Answers

You have good example of how to prevent C# auto property from serialization.

Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations.

so you can't set 'NonSerialized' on C# auto property but if the property with baking up field like your second example you can set it like you did. Then both property and field will not serialized.

In second case compiler will ignore the property because underline field is Non serialized and you will not get exception like first case.

If you want to serialize then you have to set Serializable property on UsingClass but if you don't need to serialize you can do as second method or by using [XmlIgnoreAttribute] on your auto property

like image 174
Damith Avatar answered Jun 19 '26 05:06

Damith


You have to decide whether you want to serialize data in UsingClassMember or not.

If you want to serialize it, you mark UsingClass with [Serializable]. Later when deserializing your data you will get the value of this property as it was before the serialization.

If you do not want to serialize it, you mark corresponding field with [NonSerialized]. In this case, the property will be null after deserialization (unless custom deserialization is used).

Only you can decide which approach to choose based on the meaning of your property and the purpose of serialization in your use case.

like image 37
Andrey Shchekin Avatar answered Jun 19 '26 05:06

Andrey Shchekin