Looking for the pesky little differences between C# and VB.NET, I stumbled over this nice question by Micah Martin on default values for generics in VB.NET as compared to C#. Actually there were 3 questions, so I did a bit of post-editing:
How do I create the default for a generic in VB.NET? in C# I can call:
T variable = default(T);
- How do I do this in VB?
- If this just returns null (C#) or nothing (VB.NET) then what happens to value types?
- Is there a way to specify for a custom type what the default value is? For instance what if I want the default value to be the equivalent to calling a parameterless constructor on my class.
User Konrad Rudolph – Stack Overflow. promptly gave three answers:
Question 1:
Dim variable As T
‘ or ‘Dim variable As T = Nothing
‘ or ‘Dim variable As New T()
Notice that the latter only works if you specifiy either theNew
or theStructure
constraint for the generic type.Question 2:
For value types all members of the struct are “nulled” out, i.e. all reference type members are set to
null
(Nothing
) and all value types are in turn nulled out. And no, sincestring
is a reference type, it does not result in""
for strings as suggested in the other answer.Question 3:
No, there’s no way to specify this. There are some threads about this on Stack Overflow already, e.g. here. Jon has posted an excellent explanation why this is.
–jeroen