Lars-Erik
Lars-Erik

Reputation: 311

Make a DataMember in a DataContract use implicit cast to string operator

Anyone know if it's possible to use attributes only to make DataContract serialization use the implicit cast to string operator of the type of a property in a class?

For instance:

[DataContract]
public class Root
{
    [DataMember]
    public Element Member { get; set; }
}

public class Element
{
    private string value;

    private Element(string value)
    {
        this.value = value;
    }

    public static implicit operator string(Element element)
    {
        return element.value != null ? element.value : "";
    }

    public static implicit operator Element(string value)
    {
        if (Something()) return new Element(value);
        throw new InvalidCastException()
    }
}

(This is just written by hand in a hurry, disregard any compilation issues etc.)

Lars-Erik

Upvotes: 1

Views: 2178

Answers (2)

Ivan G.
Ivan G.

Reputation: 5215

There is a reason for not doing this. Data Contracts are supposed to be simple cross-platform data transfer objects so I wouldn't put magic there. Create a non-serializable accessor property converting basic type to what you need.

Upvotes: 3

Olivier
Olivier

Reputation: 5688

An easy way to achieve this (easier than dealing with serialization issues) would be something like this :

[DataContract]
public class Root
{
    [DataMember]
    public string MemberString { get{ return (string)this.Member; } set{this.Member=(Element)value;} }

    public Element Member { get; set; }
}

Upvotes: 1

Related Questions