Properties Just Syntactic Sugar?

Eron Wright shows the difference between property accessors and methods, and declares that property syntax in .NET is not syntactic sugar.

I get his intent; Eron is speaking about proper class design w.r.t. properties and methods.  However, his point needs a little clarification.  First, try to compile the following class:

 class Class1
{
 public string foo
 {
  get{return ("Hello, world");}   
 }

 public string get_foo()
 {
  return ("Hello, world, again.");
 }
}

You will get a compiler error:

Class 'MyApp.Class1' already defines a member called 'get_foo' with the same parameter types

There is the first hint that Properties are actually a little sugary than at first blush.  Consider a very simple class with only a property accessor “foo“:

 class Class1
{
 public string foo
 {
  get
  {    
   return ("Hello, world");
  }
 }
}

Build the assembly, then use ILDASM to inspect our class that contains a single property accessor.  Quite a bit was cut for brevity here, but it illustrates the point:

.method public hidebysig specialname
instance string get_foo() cil managed
{
// Code size 10 (0xa)
.maxstack 1
.locals init ([0] string CS$00000003$00000000)
IL_0000: ldstr "Hello, world"
IL_0005: stloc.0
IL_0006: br.s IL_0008
IL_0008: ldloc.0
IL_0009: ret
} // end of method Class1::get_foo

.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Class1::.ctor

.property instance string foo()
{
.get instance string ConsoleApplication3.Class2::get_foo()
} // end of property Class1::foo

You can see that our Get property accessor is, under the covers, interpreted as a method prefix with the name “get_“.  Note that property declarations will change a bit.

Eron also mentions a potential issue with serializing the following class:

 public class Customer
{
 public int CustomerID;
 public string FirstName;
 public string LastName; 
 public Order[] Orders;
}

The point he is conveying here is that serializing public fields is problematic using the XmlSerializer.  His solution is to use a public method so that the serializer will not serialize the data (only public fields and properties with both get and set accessors can be serialized).  However, there is one more solution for preventing the serialization of the Orders field: the System.Xml.Serialization.XmlIgnoreAttribute.

 public class Customer
{
 public int CustomerID;
 public string FirstName;
 public string LastName; 
 [System.Xml.Serialization.XmlIgnore()]
 public Order[] Orders;
}