Handling Null Values in F#

前端 未结 6 896
不思量自难忘°
不思量自难忘° 2020-12-13 00:25

I need to interop with some C# code with F#. Null is a possible value that it is given so I need to check if the value was null. The docs suggest using pattern matching as s

6条回答
  •  孤街浪徒
    2020-12-13 00:49

    If you have a type that has been declared in C# or a .NET library in general (not in F#) then null is a proper value of that type and you can easily compare the value against null as posted by kvb. For example, assume that C# caller gives you an instance of Random:

    let foo (arg:System.Random) =
      if arg <> null then 
        // do something
    

    Things become more tricky if the C# caller gives you a type that was declared in F#. Types declared in F# do not have null as a value and F# compiler will not allow you to assign them null or to check them against null. The problem is that C# doesn't do this check and a C# caller could still give you null. For example:

    type MyType(n:int) =
      member x.Number = n
    

    In that case, you need either boxing or Unchecked.defaultOf<_>:

    let foo (m:MyType) =
      if (box m) <> null then
        // do something
    
    let foo (m:MyType) =
      if m <> Unchecked.defaultOf<_> then
        // do something
    

提交回复
热议问题