Monday, May 12, 2014

old school C# getsetters before the 3.0 stuff

Today we write getsetters in C# like so:

public string PendingRequest { get; set; }

 
 

These are techinically called auto-properties. The 3.0 framework uses the same compiler as the 2.0 framework so anything "new" in the 3.0 framework is really doing what it does with compiler tricks. If you look at the CLR for an auto-property you will see something like so:

private string _pendingRequest;
public string PendingRequest
{
   get
   {
      return _pendingRequest;
   }
   set
   {
      _pendingRequest = value;
   }
}

 
 

The example above is actually a C# 2.0 style getsetter, but the CLR for both this example and the example at the very top with an auto-property should look about the same. Yawn? Is that your response? Well, you should care about the old way to do getsetters because you may hack them into doing interesting things like this:

public string PendingRequest
{
   get
   {
      TimeSpan timeSpan = DateTime.Now.Subtract(WhatTimeWasItEarlier());
      return timeSpan.Days + " Day(s) " + timeSpan.Hours + " Hour(s)";
   }
}

 
 

In an example of warping a getsetter, herein I've decided I do not care about setting, just getting, so I've thrown out the set and the private field that was a backing store. I've added logic to the get to calculate a TimeSpan by substracting one DateTime from another and then I've crafted a string using the TimeSpan. This isn't the best example. A better example might be an expanded setter that sets more than the backing store field. Perhaps whenever you update FirstName or LastName on a Person the act could update FullName, etc.

No comments:

Post a Comment