Chandimal
Chandimal

Reputation: 123

C# Stop a class from serializing

I need to stop a class from getting serialized if it is in a collection, since I don't have control over the parent class property that is returning the collection. Without implementing ISerializable is there any solution?

public class NonControllable{
    Collection children;
}

public class MyClass : NonControllable {
    // NEED TO STOP Serializing children property.
}

Upvotes: 1

Views: 962

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062620

Since yoy have the [xml] tag, you would want (at the parent level):

[XmlIgnore]
public Foo Bar {...}

however, you can't control this at the type level. The type exposing the member has to define it.

An alternative is to use XmlAttributeOverrides when creating the XmlSerializer.

Note that ISerializable makes no impact on xml serialization; you would need IXmlSerializable, which is (IMO) a pain to implement robustly.

Upvotes: 4

Brian Scott
Brian Scott

Reputation: 9361

Simply mark the property with a non serializable attribute and the serialization will not occur.

See the following example;

public class MyClass : NonControllable {

    // Property that is not serialized.
    [NonSerialized()] 
    public string myProperty; 
}

Upvotes: 1

Related Questions