.NET’s “implicit operator”

photo by Adam Sherez on Unsplash

This post is inspired by a pull request that David Kemp made for my SparkyTools.DependencyProvider NuGet package.

The package is used to improve testability of classes that use dependencies that aren’t easily mockable (e.g. System.DateTime):

using SparkyTools.DepndencyProvider;
public class Foo
private readonly Func<DateTime> _getDate;

public Foo(DependencyProvider<Func<DateTime>> currentTimeProvider)
_getDate = currentTimeProvider.GetValue();

public void DoSomethingWithDate()

The package’s DependencyProvider<T> class has a couple of different ways to create a new instance:

var testDate = new DateTime(2008, 7, 4, 13, 52, 00);
// verbose / tedious:
var prod1 = new Foo(
new DependencyProvider<Func<DateTime>>(() => DateTime.Now);
var test1 = new Foo(
new DependencyProvider<Func<DateTime>>(() => testDate;
// terser / better:
var prod2 = new Foo(DependencyProvider.Create(() => DateTime.Now);
var test2 = new Foo(DependencyProvider.Create(() => testDate);

The DependencyProvider.Create syntax is pretty succinct, but what if you could just code this?:

var prod3 = new Foo(() => DateTime.Now);
var test3 = new Foo(() => testDate);

You can, thanks to the magic of .NET generics and the implicit operator. This code in the DependencyProvider<TDependency> class:

public static implicit operator 
DependencyProvider<TDependency>(TDependency value)
return new DependencyProvider<TDependency>(value);

…tells the compiler “Yo, If you see some code requiring a DependencyProvider<TDependency> instance and the developer supplies a TDependency argument, call the DependencyProvider<TDependency> constructor to implicitly convert the argument into a new instance of DependencyProvider<TDependency>!”

Thanks to David for reminding me of this “hammer”. I’m off to look at my Sparky suite of NuGet packages to see if there are any other “nails” I can pound with it (and at this point, everything looks like a nail! 🤪)

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.