Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# - DataContract Serialization - Base Classes, Inheritance and Overrides

Good day everyone,

I'm an independent game developer who has, in the past, primarily worked with XNA and, at the other extreme, commercial toolsets. The reach of XNA is pretty limited, however, and I'm building a cross-platform abstraction layer to target multiple platforms.

To cut a long story short, I've needed xml serialization that's accessible more broadly than [Serializable], and I've been pointed to data contracts. I've been doing a lot of research, but can't find any good information about some of the basics of the system, pertaining to inheritance and overrides.

The crux of my question is...

[DataContract]
public class Node
{
    private string name;

    public string Name { get { return name; } set { name = value; } }
    public virtual float Rotation { get { return 0f; } set { } }
}

[DataContract]
public class FancyNode : Node
{
    private float rotation;

    public override float Rotation { get { return rotation; } set { rotation = value; } }
}

If I serialize a 'FancyNode', will 'Rotation' be properly serialized, and will 'Name' be serialised?

Follow-up Question: I meant to ask earlier, but couldn't recall at the time. How does the serializer handler overriden [IgnoreDataMember] properties? For example...

[DataContract]
public class Simple
{
    [IgnoreDataMember]
    public virtual string Value { get { return ""; } set { } }
}

[DataContract]
public class Complex : Simple
{
    private string value;

    public override string Value { get { return value; } set { this.value = value; } }
}

Would 'Value' in 'Complex' be serialized? Some answers are suggesting that if no [DataMember] tags are used, all properties will be serialized. If so, does the [IgnoreDataMember] attribute of the base class have any bearing?

like image 614
Nathan Runge Avatar asked Jun 20 '12 08:06

Nathan Runge


1 Answers

As far as I know, DataContract is an 'opt-in' serialization method, i.e. stuff isn't serialized unless you decorate it (tell the serializer you want to serialize it)

So for the above example, you would need to add [DataMember] to the properties you wanted to serialize

With the standard Serializable attribute, the serializer looks at all fields and only ignores those which you mark as NonSerialized

Some examples here:

http://jamescbender.azurewebsites.net/?p=651

Check the notes section on this for info on what gets serialized and a rough outline of what happens:

http://msdn.microsoft.com/en-us/library/ms733127.aspx

Edit: Also I can't see any reason why any of the fields once marked as [DataMember] wouldn't be serialized properly. The DataContract method of serialization can also deal with circular references - something that other serialization sometimes has trouble with:

http://msdn.microsoft.com/en-us/library/hh241056.aspx

like image 167
Charleh Avatar answered Oct 03 '22 00:10

Charleh