Wednesday, September 3, 2008

Checking/Asserting for not null with a Generic Method

In my code I like to check parameters for entry conditions and assert where the parameters do not match with the contract for the method. I prefer to have a quick to type and one-line method to do so. My initial code to do this looked like the following:



public static void IsNotNull(object obj, string message)


{


    if (obj == null) throw new NullReferenceException(message);


}


That was great and it allowed me to check for null parameters inside of a method easily with some code that looks like this:



Assert.IsNotNull(account, "account was null");


Assert.IsNotNull(account != null, "account was null");


But notice that the signature of the method allows for the erroneous account != null to be used. To prevent this I changed the signature of method to:



public static void IsNotNull<T>(T obj, string message)


    where T : class


{


    if (obj == null) throw new NullReferenceException(message);


}


Now when you inadvertently put in a value type, it will correctly report this as an error. If you are new to Generics, then you might assume that you must identify the type. Either of the two usages below are equivalent thanks to the compiler inferring the type of the template ‘T’.


Assert.IsNotNull(account, "account was null");

Assert.IsNotNull<Account>(account, "account was null");


If you use Resharper, it will show you that you can safely remove the <Account> from the method call reporting that ‘Type argument specification is redundant.

No comments:

Post a Comment