Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Property from being serialized

Tags:

c#

wpf

I tried something like this:

    [NonSerialized]
    private string _DecodeText;
    public string DecodeText { get { return _DecodeText; } set { _DecodeText = value; } }

But it does not work. "DecodeText" is still in the serialized file. How can i prevent the property from serializing?

like image 909
Display Name Avatar asked Dec 06 '11 09:12

Display Name


People also ask

Are private fields serialized?

So yes, it will serialize private fields if you mark them with [SerializeField] attribute.

What does serialized content mean?

What is Serialized Content? Content serialization involves taking one concept or topic and turning it into many smaller chunks or installments, so you develop a series based on one idea. For example, the Lord of the Rings trilogy was too large for one story, so Tolkien broke it down into three parts.

Are properties serialized C#?

Only collections are serialized, not public properties.

What is non serialized attribute in serialization?

When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized. For example, you can use this attribute to prevent the serialization of sensitive data.


3 Answers

I was able to use the following and not have the property serialized (.NET 4.0):

private string _DecodeText;
[System.Xml.Serialization.XmlIgnore]
public string DecodeText { get { return _DecodeText; } set { _DecodeText = value; } }
like image 78
John Avatar answered Sep 18 '22 16:09

John


I Suspect you're using the XmlSerializer? If so use the [XmlIgnore] attribute instead.

This should be applied to the property instead of the backing field as the XmlSerializer serializes public fields and properties (whereas the BinaryFormatter uses refelction to get at the private fields - hence the marking of the private field with NonSerialized when using a BinaryFormatter).

like image 26
Russell Troywest Avatar answered Sep 21 '22 16:09

Russell Troywest


Updated Answer

The [NonSerialized] atttibute is on the variable not the property, but it cannot be on the attribute. So it is not going to help.

One way to prevent the property being serialized is to add a method

public bool ShouldSerializeDecodeText() {
   return false;
}

and this (for the XmlSerializer at least) will prevent the property being serialized.

If you don't want to add lots of methods to the class just for serialization you might try inheriting from it and adding the methods to the derived class.

hth, Alan.

like image 2
AlanT Avatar answered Sep 18 '22 16:09

AlanT