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