Why can't I add None
to a System.Collections.Generic.Dictionary
of Option
? Is it an expected behavior or a bug in Mono?
F# Interactive for F# 3.1 (Open Source Edition)
Freely distributed under the Apache 2.0 Open Source License
For help type #help;;
> open System.Collections.Generic;;
> let d1 = new Dictionary<int option, int>();;
val d1 : Dictionary<int option,int> = dict []
> d1.Add(None, 1);;
System.ArgumentNullException: Value cannot be null.
Parameter name: key
at System.ThrowHelper.ThrowArgumentNullException (ExceptionArgument argument) in <filename unknown>:line 0
at System.Collections.Generic.Dictionary`2[TKey,TValue].Insert (System.Collections.Generic.TKey key, System.Collections.Generic.TValue value, Boolean add) in <filename unknown>:line 0
at System.Collections.Generic.Dictionary`2[TKey,TValue].Add (System.Collections.Generic.TKey key, System.Collections.Generic.TValue value) in <filename unknown>:line 0
at <StartupCode$FSI_0004>.$FSI_0004.main@ () in <filename unknown>:line 0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) in <filename unknown>:line 0
Stopped due to error
> d1.Add(Some 10, 1);;
val it : unit = ()
I'm using Mono on OS X.
$ mono --version
Mono JIT compiler version 4.2.0 (Stable 4.2.0.179/a224653 Tue Oct 6 11:28:25 PDT 2015)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
TLS: normal
SIGSEGV: altstack
Notification: kqueue
Architecture: amd64
Disabled: none
Misc: softdebug
LLVM: supported, not enabled.
GC: sgen
Its not a bug. Option<'T> uses the attribute [CompilationRepresentation( CompilationRepresentationFlags.UseNullAsTrueValue) which causes None to be represented as null.
So you actually are adding a null as a key to a Dictionary which as you know is not allowed.
For reference:
UseNullAsTrueValue: Permit the use of null as a representation for nullary discriminators in a discriminated union.
More information here Why is None represented as null?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.