c# - Activator.CreateInstance creates value of type T instead of Nullable<T> -


look @ sample code below

var genericnullabletype = typeof(nullable<>); var nullabletype = genericnullabletype.makegenerictype(typeof(bool)); var returnvalue = activator.createinstance(nullabletype, (object)false); 

for reason returnvalue variable of type bool , not bool?. why , how avoided?

upd: here screenshot vs enter image description here

in particular case using overload of createinstance returns object. nullable<t> struct hence represented object need boxed. yet nullable<t> can't boxed rules of clr. instead underlying value or null used. why raw bool here instead of bool?.

documentation: https://msdn.microsoft.com/en-us/library/ms228597.aspx

edit

there seems confusion around determining whether type of value nullable or not. in particular it's been pointed out following prints system.boolean , not system.nullable``1[system.boolean]:

var x = (bool?)true; console.writeline(x.gettype()); 

this code falling prey boxing. call gettype has implicit boxing operation because it's invocation of virtual method on object, not method on nullable<t>:

il_0009: ldloc.0 il_000a: box valuetype [mscorlib]system.nullable`1<bool> il_000f: call instance class [mscorlib]system.type [mscorlib]system.object::gettype() il_0014: call void [mscorlib]system.console::writeline(object) 

the safest way print out actual type of var value following trick generics:

static void printtype<t>(t value) {     console.writeline(typeof(t)); }  printtype(x);  // prints system.nullable`1[system.boolean] 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -