Search code examples
c#.net-core.net-6.0

Can you tell by Reflection which string is nullable and which is not?


I have these 2 types:

  1. Type nrvt = typeof(List<string?>); // nullable string generic argument
  2. Type nnrvt = typeof(List<string>); // non-nullable string generic argument

Can I tell (via Reflection) which has nullable and which has non-nullable strings in .NET 6?

There's a NullabilityInfoContext but handles object-related stuff (Properties, Fields, Events and Parameters). Not finding anything for this case.


Solution

  • No. The IL for both constructs is the same (SharpLab link):

    IL_0000: nop
    IL_0001: ldtoken class [System.Collections]System.Collections.Generic.List`1<string>
    IL_0006: call class [System.Runtime]System.Type [System.Runtime]System.Type::GetTypeFromHandle(valuetype [System.Runtime]System.RuntimeTypeHandle)
    IL_000b: stloc.0
    IL_000c: ret
    

    where local variable 0 is class [System.Runtime]System.Type. So when compiled there is no difference between the two expressions.