I Am Not Myself

Bills.Pay(Developer.Skills).ShouldBeTrue()

Using the Implicit Operator in C# for Maximum Nerdy Good Times

My current team works with a lot of data. We represent that data with explicit types. For example if a string represents a Name we create an explicit type called Name like so:

public struct Name
{
  private readonly string _string;
  public Name(string name){ _string = name; }
  public override string ToString() { return _string } 
}

This makes things nice for testing purposes as these value structs are comparable for free and are clearly named what the value represents. The downside is if you need to set up a bunch of test data for a unit test you can run into code that looks like this:

 Name name = new Name("Name");
 IEnumerable<Name> names = new[] { new Name("Tom"), new Name("Dick"), new Name("Harry"), }

This will quickly give you carpal tunnel with all the ceremony required to create all the instances. It would be nice if we could reduce some of the noise and we can via use of the implicit operator. All we need to do is add the following operator logic to our struct.

public struct Name
{
  private readonly string _string;
  public Name(string name){ _string = name; }
  public override string ToString() { return _string } 
  public static implicit operator Name(string name) { return new Name(name); }
}

What does this buy us? How does the following syntax strike you?

 Name name = "Name";
 IEnumerable<Name> names = new[] { "Tom", "Dick", "Harry", }

We are used to using implicit typing from on the left hand side of a statement, were you aware that it can be used on the right hand side? I wasn’t. But basically this is how collection initializers work. Nice eh?

Thanks to Robert Ream for showing me this. It was fun working with someone with such a deep understanding of the language and functional development, even if it was a brief time.

5 responses to “Using the Implicit Operator in C# for Maximum Nerdy Good Times

  1. arnisl March 28, 2012 at 1:34 pm

    var names = new[] { “Tom”, “Dick”, “Harry”};

    looks even better. also – try AutoFixture for test data setup.

  2. Pingback: Friday Links #197 | Blue Onion Software *

  3. MB August 7, 2012 at 11:21 am

    Honestly, besides the gwiz factor, why bother? You’ve just added yet another ‘trick’ that people on your project need to know in order to read the code. Most likely on first glance, people are just gonna see it as an array of strings.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: