Search code examples
c#.netwcfdatacontractserializer

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


Solution

  • 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; }
    }