Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for generics

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.
like image 922
Micah Avatar asked Dec 09 '08 20:12

Micah


People also ask

What is the default value for type T?

If T is a class or interface type, default(T) is the null reference. If T is a struct, then default(T) is the value where all the bits are zero. This is 0 for numeric types, false for bool , and a combination of both of these rules for custom struct s.

Do generics increase performance?

With using generics, your code will become reusable, type safe (and strongly-typed) and will have a better performance at run-time since, when used properly, there will be zero cost for type casting or boxing/unboxing which in result will not introduce type conversion errors at runtime.

How does generics work in C#?

When a generic type is first constructed with a value type as a parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate locations in the MSIL. Specialized generic types are created one time for each unique value type that is used as a parameter.


2 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 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.

like image 181
Konrad Rudolph Avatar answered Oct 05 '22 23:10

Konrad Rudolph


Actually folks the correct way of doing this is to cast the null (Nothing) type as your generic type as follows:

Dim tmpObj As T = CType(Nothing, T)

If you want to return the default value for the generic you simply return CType(Nothing, T)

like image 44
user234662 Avatar answered Oct 06 '22 00:10

user234662