Active pattern: NULL

Category:
Active patterns
Description: Active pattern determines if the input value is null. When sample is executed under debug mode, it throws exception which is expected behavior.
Code:
let ActivePatternSample3() =     
let inline isNull v = System.Object.ReferenceEquals(v, null)
let (|Null|_|) value = if isNull value then Some() else None
let check v =
match v with
| Null -> nullArg "v is null"
| _ -> ()
check null

Execution Result:
Exception raised: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: v is null
at Microsoft.FSharp.Core.Operators.Raise[T](Exception exn)
at Samples.Others.check@482-1T.Invoke(a v) in C:\MyCode\Samples\SampleProject\SampleProject\Samples.Others.fs:line 484
at Samples.Others.ActivePatternSample3() in C:\MyCode\Samples\SampleProject\SampleProject\Samples.Others.fs:line 486
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Support.Helper.Utils.samples@190-3.Invoke(Unit unitVar0) in C:\MyCode\Samples\SampleProject\SampleProject\Supportive.Helper.fs:line 190
at Support.Helper.Utils.getExecutionResult(FSharpOption`1 sampleOption) in C:\MyCode\Samples\SampleProject\SampleProject\Supportive.Helper.fs:line 256

Last edited Sep 14, 2011 at 3:18 AM by ttliu2000, version 1

Comments

Thorium Mar 3, 2012 at 9:34 AM 
Best practice: We should never have null in F#.
Null means unassigned.
If we don't have mutable state, things are always assigned by design.