Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I create the default for a generic in VB? in C# I can call:

T variable = default(T);
  1. How do I do this in VB?
  2. If this just returns null (C#) or nothing (vb) then what happens to value types?
  3. 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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 specify the Structure constraint for the generic type (for reference types, New T() in VB does something else than default(T) in C#).

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, since string 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...