While working with generics, I’ve realized this about their behavior with default values for types in C# and VB.NET. For example, if you have the following simple generic method in C#:
public static T GetDefault<T>()
{
return null;
}
For those C# inclined, you will notice that this function will not compile. Why? Since the method is generic (and without constraints), the compiler cannot assure the value of null for the type. In other words, the call
int i = GetValue<int>();
obviously breaks this assumption. Fortunately, the language offers the default construct that will return, well, the default value for a generic type. In other words, for int it will return 0 and for string it will return null. Using this construct, the new method will look like this,
public static T GetDefault<T>()
{
return default(T);
}
This method will now make the compiler happy! I wanted to see if VB.NET had a similar construct for default values. I converted the original C# method to VB.NET, this is what it looks like
Public Shared Function GetDefault(Of T)() As T
Return Nothing
End Function
To my surprise, the method compiled! WTF?!?! I'm fluent in VB.NET, but I'm no expert on it. I would think that setting the value of Nothing to a primative type, would cause the the compiler to freak! Thinking about it, I tried this code
Dim i as Integer = Nothing
The VB.NET compiler said nothing about my bogus assignment!! The equivalent C# code,
int i = null;
makes the C# compiler raise an error (as expected). (Note: C# 2.0 supports the concept of nullable types)
VB.NET people, care to explain? You can download my sample application from here.