开发者

correct way to check if nullable has a value

开发者 https://www.devze.com 2023-03-04 06:27 出处:网络
assuming v is a nullable, I\'m won开发者_如何学Cdering what are the implications / differences between these usages:

assuming v is a nullable, I'm won开发者_如何学Cdering what are the implications / differences between these usages:

VB:

  1. If v Is Nothing Then
  2. If v.HasValue Then

C#:

  1. if (v == null)
  2. if (!v.HasValue)


There's no difference - Is Nothing is compiled to use HasValue. For example, this program:

Public Class Test
    Public Shared Sub Main()
        Dim x As Nullable(Of Integer) = Nothing
        Console.WriteLine(x Is Nothing)
    End Sub
End Class

translates to this IL:

.method public static void  Main() cil managed
{
  .entrypoint
  .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) 
  // Code size       24 (0x18)
  .maxstack  2
  .locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0)
  IL_0000:  ldloca.s   V_0
  IL_0002:  initobj    valuetype [mscorlib]System.Nullable`1<int32>
  IL_0008:  ldloca.s   V_0
  IL_000a:  call       instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
  IL_000f:  ldc.i4.0
  IL_0010:  ceq
  IL_0012:  call       void [mscorlib]System.Console::WriteLine(bool)
  IL_0017:  ret
} // end of method Test::Main

Note the call to get_HasValue().


There is no difference. You always get the same result. Some time ago I wrote a few unit test that check different behaviors of nullable types: http://www.copypastecode.com/67786/.


Absolutely no difference. This is just your style preference.

Those two lines of code will generate absolutely identical IL code:

if (!v.HasValue)

if (v == null)

You can see in IL that in both cases Nullable::get_HasValue() is called.

Sorry, I did the sample in C#, not VB.


Use the HasValue property

If v.HasValue Then
    ...
End
0

精彩评论

暂无评论...
验证码 换一张
取 消