Creating a Value Defaulter with C# Generics

C# generics are an incredibly flexible tool which can help C# developers overcome a whole host of challenges. Recently I was asked something that drew upon the use of generics to create an elegant solution to the problem

The Challenge

So this little exercise I did in response to a question posed by one of my coworkers a few weeks ago. He’s a super smart client side developer who really enjoys functional coding. On this occasion he was working with C#, and was interested to see if it had similar type flexibility. He wanted to know if it was possible to set the value of a type to a default value, if it was below a certain threshold. So, if the value is lower than 10, then it should be set to 10. Otherwise it should be left as it is.

The key point was that it should be able to take any type and default it correctly. On my first try I created a single method that determined the type of the value. It then converted a string version of the default value to that type using Convert.ChangeType, and assigned it back. I wasn’t happy with the fact that it relied on side-effects though.

The Final Solution

Of course, the cleanest solution – and the one I ended up going with – is to use generics. Together with lambda expressions they are my favorite feature in C# and turned a clunky multiple line solution in to a simple one liner. In fact, the final method simply looked like this:

public T MinOrValue(T value)
    return value.CompareTo(_minimumValue) >= 0 ? value : _minimumValue;

It’s not going to do you much good out of context, so check out the source code on GitHub. The generic version is better than the original on two fronts. First, as mentioned, it’s more concise. Second the GenericValueComparer class which wraps it doesn’t just take in the type, but also what the default value should be too.

An unintended side effect of the implementation was the ability to extend it to work with any type that implements IComparable. The unit tests show an example of how to default the value of a simple custom type. This class compares its own properties by implementing CompareTo(), and is defaulted to the provided value if they fall outside the range.

Leave a Reply

Your email address will not be published. Required fields are marked *