C#6 introduced some good short-hand methods of dealing with properties. I actually like them, as a result of they take away a lot boilerplate code. But as with all new instruments, it’s simple to make use of them wrongly till they’re acquainted.

These are two makes an attempt to declare a readonly property that preserves the time stamp of when the article was created. They look related, however solely considered one of them is true.

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

The distinction is that the primary one is an expression bodied member – a operate that executes each time the getter is executed, whereas the second is a read-only auto property that’s initiated as soon as when the article is created. It is in fact the latter behaviour we wish for a creation time stamp. A small take a look at program reveals the distinction.

  var s = 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 reveals how A is modified after the sleep, whereas B retains the creation timestamp.

A: 636435047872825754, B: 636435047872825754
A: 636435047873833584, B: 636435047872825754

If we develop the short-hand code into acquainted old-school C#, the distinction is made clear.

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

While I do like the brand new short-hand syntax, it actually has drawbacks comparable to this delicate(?) distinction that may introduce nasty bugs. Syntax options that make the language extra environment friendly for skilled builders additionally make the language more durable to be taught for freshmen.


Posted in
C# on 2017-10-13 | Tagged Language Basics




Source link