Using Default Values in Generic Method

There are times when you want to assign default values to your variables. For instance if you have a reference type variable the default value will be null. If it is a value type you could assign 0. But how do you check in a generic method if the value the user has passed in is a default value or not. The reason being every type has its own default value, you cant check against null because the user may have passed in value type which cannot be checked against null value. What if the user has passed in datetime data type, in that case the default value would DateTime.Min.

To address this problem C# 2.0 introduced a new operator called default which allows you to get a default value for a variable whose data type is unknown at design time. Let's look at a generic method in which I check to see if the value user has passed in is a default value or not.

image

 CWindowssystem32cmd.exe

In the above example, I am placing a constraint on the generic type that it must implement IComparable<T>. The reason for forcing this constraint is to actually call the compareTo method on IComparable interface to check if two values are greater than, equal to or same. Since we don't know at design time what type we are going to pass, we rely on default operator to get us the right default value based on the type passed in at runtime.

In the first case I pass in 1, an integer which evaluates to 1 because 1 is greater than the default value of 0. In the second case I pass in 0 which is equal to default value of 0 for integer types. In the string value of test, the result evaluates to 1 because the default value for reference type is null and anything that is passed in that is not null is always greater than null. In the last 2 cases I get 1 and 0 because the default value for datetime operator is DateTime.Min so when you pass in DateTime.Min, the value returned is 0.

Notice in order to compare two values, I did not make use of == or != operator and that is because they can only be used with reference type variables. When there is no constraint on the generic type that it must be a reference type, use of == operator will return incorrect results for value type variables.

Published Saturday, April 19, 2008 1:42 AM by zhirani

Comments

No Comments