views:

48

answers:

2

As an example from this site: http://www.c-sharpcorner.com/UploadFile/ankithakur/ExceptionHandlingWCF12282007072617AM/ExceptionHandlingWCF.aspx

[DataContract]
public class MyFaultException
{
    private string _reason;

    [DataMember]
    public string Reason
    {
        get { return _reason; }
        set { _reason = value; }
    }
}

Is there any reason why is that approach is favored, considering that WCF started in .NET 3.0 and C# 3 already has automatic property. Why it's not written like the following?

[DataContract]
public class MyFaultException
{
    [DataMember]
    public string Reason { get; set; }
}
+4  A: 

C# 3 came with .NET 3.5 - i.e. after .NET 3.0.

Of course, there could be other reasons for it being a bad idea to use automatic properties for DataMember properties, but that's certainly one reason why you could be seeing examples like that.

(Admittedly the page you gave as an example was written in January 2008 - but as VS2008 was only released in November 2007, the author may well not have upgraded by that point.)

Jon Skeet
+1 largely to see just how high your rep can go ;) Oh, and for a nice insight. Must read your book.
Lazarus
+1 For noting the timeline. So it could just be that, everyone gets excited with WCF very early, and they started documenting it, but still used to with explicitly-backed properties. Still interested with other reasons why automatic properties is a bad idea(technical-wise) for WCF, if there is none, I will just use automatic properties consistently
Michael Buen
@Michael: I'll ping Marc Gravel, who's done a lot more with WCF than I have.
Jon Skeet
@Jon: Thanks a ton :-)
Michael Buen
+3  A: 

Just for completeness beyond Jon's point, another point here is that in many (not all) scenarios the data-contract is generated from some kind of model (dbml, EF, wsdl, proto, etc). As such, there is no real additional cost to explicit properties, and explicit properties work on more language versions.

Additionally, the template code might include partial methods to allow pre/post operations, and other framework code. That part of the template may have been omitted from the published example for brevity.

Finally, data-contracts can optionally be specified against the field, allowing read-only properties etc:

[DataContract]
public class MyFaultException
{
    [DataMember(Name="Reason")]
    private string _reason;
    public string Reason { get { return _reason; } }
}
Marc Gravell
is automatic property safe on WCF? versioning-wise and other factors
Michael Buen