6 people like it.

How to check whether an F# function/method has been initialized

Sometimes, we may run into this kind of situation that we want to check if the given method/function has been initialized. We all know this is fairly easy in C#, since we can use delegate to invoke the function , then verify if the value of delegate is null. But in F# , delegate is rarely needed because F# can treat a function as a value, without the need for any wrapper. So , here is an easy way to solve this problem.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
type public Class1() =
    [<DefaultValue>]
    val mutable public onCancel : System.Object -> unit
 
    member public this.Verify() = 
        if box(this.onCancel) = null then
            ()//do something
Multiple items
type Class1 =
  new : unit -> Class1
  val mutable onCancel: Object -> unit
  member Verify : unit -> unit

Full name: Script.Class1

--------------------
new : unit -> Class1
Multiple items
type DefaultValueAttribute =
  inherit Attribute
  new : unit -> DefaultValueAttribute
  new : check:bool -> DefaultValueAttribute
  member Check : bool

Full name: Microsoft.FSharp.Core.DefaultValueAttribute

--------------------
new : unit -> DefaultValueAttribute
new : check:bool -> DefaultValueAttribute
Class1.onCancel: System.Object -> unit
namespace System
Multiple items
type Object =
  new : unit -> obj
  member Equals : obj:obj -> bool
  member GetHashCode : unit -> int
  member GetType : unit -> Type
  member ToString : unit -> string
  static member Equals : objA:obj * objB:obj -> bool
  static member ReferenceEquals : objA:obj * objB:obj -> bool

Full name: System.Object

--------------------
System.Object() : unit
type unit = Unit

Full name: Microsoft.FSharp.Core.unit
val this : Class1
member Class1.Verify : unit -> unit

Full name: Script.Class1.Verify
val box : value:'T -> obj

Full name: Microsoft.FSharp.Core.Operators.box
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/bW
Posted:11 years ago
Author:ZackZhou
Tags: f# , null