Home > other >  What is the equivalent to C# default literal for a struct in VB?
What is the equivalent to C# default literal for a struct in VB?

Time:09-27

i stumbled across this C# code return default; in a method with a struct as return type. The closest translation to the default literal i have come across for VB is Return CType(Nothing, T) - however, VS is suggesting to replace this expression with nothing. Since my T is of struct (and therefore a value type which

the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null)

i was wondering what the best equivalent in VB for that would be.

Thank you in advance and best regards!

CodePudding user response:

In most cases, 'Nothing' will give you the same results as 'CType(Nothing, T)', however in other cases you lose information. e.g.,

Dim test1 = CType(Nothing, Foo)
Dim test2 = Nothing

The first local 'test1' if of type Foo, but the second is of type 'Object'. This will also affect expressions where the compiler knowing the actual type of a sub-expression changes the result of the expression. For this reason, I doubt if VS will always recommend the use of 'Nothing' over 'CType(Nothing, Foo)'. If in doubt, use the more verbose syntax to avoid loss of information.

CodePudding user response:

i was wondering what the best equivalent in VB for that would be.

Yes, in your case Return Nothing would be the appropriate replacement.

In general:

  1. default corresponds to Nothing, and
  2. default(T) corresponds to CType(Nothing, T).

The first is for situations where the compiler can be infer the type from context, and the second one for all other situations.

  • Related