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; }
}
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; } }
}
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With