December 2008 Entries

Recently, we added a SSN type to our project. I also wanted to make an implicit conversion from a string, so that when using it I could do:

   1:  SSN mySsn = "111-22-3333";

 

I came across an msdn page about how to code it and thought I'd post it here for posterity.
   1:  using System;
   2:   
   3:  namespace Examinetics.Core
   4:  {
   5:      public class SSN
   6:      {
   7:          private readonly string _ssn;
   8:   
   9:          public SSN(string ssnString)
  10:          {
  11:              _ssn = ssnString;
  12:          }
  13:   
  14:          // implicit string converter
  15:          public static implicit operator SSN(string ssnString)
  16:          {
  17:              return new SSN(ssnString);
  18:          }
  19:   
  20:          public string DatabaseValue
  21:          {
  22:              get { return _ssn.Replace("-", string.Empty); }
  23:          }
  24:   
  25:          public string DisplayValue
  26:          {
  27:              get { return  DatabaseValue.Insert(3, "-").Insert(6, "-"); }
  28:          }
  29:      }
  30:  }

This allows developers to assign a string and let the implicit converter do the work of creating an object with that string. So I can use this type as expected:

   1:  SSN mySsn = "111-22-3333";
   2:  mySsn.DatabaseValue; //111223333
   3:  mySsn.DisplayValue; // 111-22-3333

 

Now obviously, this class is missing other checks (empty strings, nulls and strings that are not valid as SSNs) I stripped all that out to highlight the implicit conversion and a possible use of implicit conversions.

Hope this is helpful.

~Lee

OK. Now that I've fully recovered from the event, I can post about it. The Kansas City Day of Dot Net was a great success. We had about 90 people, 20 speakers, 4 tracks and WAY too much food. Everybody seemed to have a great time and got some good information out of it. I got to meet some of the people I'd been chatting with online or following on twitter. A HUGE thank you goes out to Doug Butscher, Becky Isserman, Yair Segal and John Alexander. Without them, there would not have even BEEN an event. Thanks guys.

For those of you who read my blog and were waiting for the BDD series to continue, I apologize. I took the last week to catch up on some much needed rest and family time (and Christmas shopping). Part one will be posted this week with some code samples. In the mean time, you can view my presentation on Slideshare.net although the presentation is pretty sparse, the code samples will be posted with part one of the series.

Thanks for you patience.

~Lee