Thursday 23 September 2010

Tip of the day – A good use of auto implemented properties.

A very practical use of auto implemented properties could be to create a immutable lightweight class. An auto implemented property is a ‘property’ in C# without fields. The C# JIT Compiler generates the IL with a field for the auto implemented properties. (hence the name). The IL also replaces the Get and Set accessor stubs in the Properties to return and set the automatically generated field.

Take a look at the below code ( class ‘Books’). There are Title, Author and PublshedYear auto implemented properties. Notice the set is private, This makes the ‘Books’ class immutable.

autoprop

The tip is to use this kind of construct to replace structs when ever a reference type is required. Also notice that the constructor is made ‘private’. Simply because i find the factory method ‘CreateBook’  semantically appealing to call the private constructor rather than having to use the auto implemented property directly in the constructor for initializing the Books object.

Take a look at the IL for Books.,  Notice the ‘k__BackingField’ feild generated by the C# Compiler.

image

//////////////get_Author: string() IL////////////////////

.method public hidebysig specialname instance string
        get_Author() cil managed
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  // Code size       11 (0xb)
  .maxstack  1
  .locals init (string V_0)
  IL_0000:  ldarg.0
  IL_0001:  ldfld      string ConsoleApplication1.Books::'<Author>k__BackingField'
  IL_0006:  stloc.0
  IL_0007:  br.s       IL_0009
  IL_0009:  ldloc.0
  IL_000a:  ret
} // end of method Books::get_Author

 

//////////////////set_Author:void(string) IL////////////////

.method private hidebysig specialname instance void
        set_Author(string 'value') cil managed
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  // Code size       8 (0x8)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  stfld      string ConsoleApplication1.Books::'<Author>k__BackingField'
  IL_0007:  ret
} // end of method Books::set_Author

Now, a demo of using the above immutable lightweight class

democode

Happy patterns discovery..

I’ve used the MSDN example here to illustrate.

No comments:

Post a Comment