Prev | Current Page 171 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"


static int CompareToDefault (T value)
where T : IComparable
{
return value.CompareTo(default(T));
Listing 3.4 Comparing a given value to the default in a generic way
82 CHAPTER 3 Parameterized typing with generics
}
...
Console.WriteLine(CompareToDefault("x"));
Console.WriteLine(CompareToDefault(10));
Console.WriteLine(CompareToDefault(0));
Console.WriteLine(CompareToDefault(-10));
Console.WriteLine(CompareToDefault(DateTime.MinValue));
Listing 3.4 shows a generic method being used with three different types: string,
int, and DateTime. The CompareToDefault method dictates that it can only be
used with types implementing the IComparable interface, which allows us to call
CompareTo(T) on the value passed in. The other value we use for the comparison is the
default value for the type. As string is a reference type, the default value is null??”and
the documentation for CompareTo states that for reference types, everything should be
greater than null so the first result is 1. The next three lines show comparisons with the
default value of int, demonstrating that the default value is 0. The output of the last line
is 0, showing that DateTime.MinValue is the default value for DateTime.
Of course, the method in listing 3.4 will fail if you pass it null as the argument??”
the line calling CompareTo will throw NullReferenceException in the normal way.


Pages:
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183