default(T) …. eeeeeeewwwwwww


When working with generics, there will be times you want to “clear” a variable reference, eg set it to null.  In Vb.NET you can simply assign the value of Nothing, eg:

  Dim x as T

  x = Nothing


This works perfectly for all types of T, be it a Structure, a reference type, or an intrinsic type.


C# on the other hand doesn’t provide a universal way to deal with these different types.  in C#, you can only assign null to reference types.  This can cause problems with generics as you may not have the type constrained to a reference type, and considering intrinsic types are also considered to be structs, you don’t really have a way to clear them unless you call new.  So what C# has done is to give “default” a new meaning when used with generics.  So in c#

   T x = default(T);


is the equivalent of VB.NET’s


   Dim x as T


and  C#’s :


    x = default(T);


is the equivalent of Vb.NET’s

   x = Nothing


hands down I much prefer the VB.NET way of dealing with this.  Fortunately VB included the very concepts of types not being known from the very start,  so when generics came along these things just work instead of having to introduce what I consider to be ugly language hacks. 

Anyone care to bet which language will be more suited to being a fully fledged dynamic language when the time comes ??











2 Comments so far

  1.   Jason Bock on June 8th, 2005          

    Neither Definitely not C# and probably not VB

  2.   Daniel Crowley - Wilson on June 8th, 2005          

    I don’t really see a good reason to clear a variable halfway through a code block, especially if it’s a value type. If it’s a value type, it’s impossible to truly "clear" it anyway. It’s either unassigned or it has a value. I think you’ll find default(T) returns a zero whitewash on the structure, which if you are dealing with an <int>, means you’ll get a zero back.

    I see default(T) more as a nicer way to pass back an empty return value – be it a null ref for a reference type or a zero whitewash for a value type.

    That all being said, default is a horrible keyword to use, especially since we c#ers are already using it in switch statements.