Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are most DataContract's DataMembers I see on coding websites not written using automatic properties?

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 that approach is favored, considering that WCF started in .NET 3.0 and C# 3 already has automatic properties? Why is it not written like the following?

[DataContract]
public class MyFaultException
{
    [DataMember]
    public string Reason { get; set; }
}
like image 696
Michael Buen Avatar asked Aug 10 '10 15:08

Michael Buen


2 Answers

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; } }
}
like image 149
Marc Gravell Avatar answered Oct 27 '22 11:10

Marc Gravell


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.)

like image 32
Jon Skeet Avatar answered Oct 27 '22 11:10

Jon Skeet