Scrum Masters

Expression Bodied vs. Auto Read-Only Properties


& #13;. .

C# 6 brought some great short-hand methods of managing homes. I actually like them, since they eliminate much boilerplate code. However similar to all brand-new tools, it’s simple to utilize them mistakenly till they recognize.

These are 2 efforts to state a readonly residential or commercial property that maintains the time stamp of when the things was developed. They look comparable, however just one of them is right.

 class SomeClass.
 {
   public DateTime CreationTimeA =>> DateTime UtcNow;
   public DateTime CreationTimeB  {  get; }   = DateTime UtcNow;
} 

The distinction is that the very first one is an expression bodied member– a function that carries out each time the getter is performed, while the 2nd is a read-only automobile residential or commercial property that is started as soon as when the things is developed. It is obviously the latter behaviour we desire for a development time stamp. A little test program reveals the distinction.

   var s  =  brand-new SomeClass();
Console WriteLine($" A: {s.CreationTimeA.Ticks}, B: {s.CreationTimeB.Ticks} ");
Thread Sleep( 100);
Console WriteLine($" A: {s.CreationTimeA.Ticks}, B: {s.CreationTimeB.Ticks} ");

The output demonstrates how A is altered after the sleep, while B keeps the production timestamp.

 A: 636435047872825754, B: 636435047872825754

. A: 636435047873833584, B: 636435047872825754

.

If we broaden the short-hand code into familiar old-school C#, the distinction is explained.

 class SomeClass.
 {
   public DateTime CreationTimeA.
 {
     get
     {
       return DateTime UtcNow;
    } 
  } 
.
 personal DateTime creationTimeB;
.
 public SomeClass()
   {.
creationTimeB  = DateTime UtcNow;
  } 
.
 public DateTime CreationTimeB.
 {
     get
     {
       return creationTimeB;
    } 
  } 
} 

While I simulate the brand-new short-hand syntax, it definitely has disadvantages such as this subtle(?) distinction that can present nasty bugs. Syntax functions that make the language more effective for knowledgeable designers likewise make the language harder to find out for novices.

. Published in . C# on 2017-10-13|Tagged Language Essentials
. . . .

Source link .