default(T) .... eeeeeeewwwwwww
Posted
Tue, Jun 7 2005 15:31
by
bill
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 ?? 