Friday, July 27, 2007

Fun with Type Inference

Recently a co-worker of mine turned me on to the glories of Resharper. Using Resharper to optimize my code I learned that when calling a generic method, it is often not necessary to specify the type, as the compiler will work it out for you. Aside from a little less typing, I hadn't really figured out how this could be useful. Until this week.

I was writing some basic data layer code, adding parameters to a SqlCommand object. A couple of the annoying .NET/SQL Server 'gotchas' reared their heads at me yet again:

1) You can't stick a null value in as a parameter value, it has to be transformed to DBNull.Value; and
2) You can't stick a date of DateTime.MinValue into a DateTime field.

I wanted a generic function that I could simply wrap all of my parameters into, so that I didn't have to specifically remember "oh this is a date field, call this function" or "oh this variable might contain a null, call this function".

Unfortunately the DateTime comparison can't be used in a generic function, so I needed at least 2 functions, but thanks to overloading and type inference I can still use the same call everywhere. Here are my two functions:

Normally when you call a generic method, you specify the type in the call, such as:

If this were always the case, my calls would differ everywhere, and especially when using DateTime's because the DateTime overload is not generic.

But thanks to Type Inference, I can now write code like the following, without having to care what type of variable I'm dealing with:

No comments: