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.

Follow me on Mastodon!