Home > Back-end >  Can you tell by Reflection which string is nullable and which is not?
Can you tell by Reflection which string is nullable and which is not?

Time:06-10

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.

CodePudding user response:

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.

CodePudding user response:

No, nrvt and nnrvt are the same type.

Nullable Reference Types are only a compiler instruction intended to prevent warnings about objects potentially being null in a #nullable conext.

string? is not creating a Nullable<string> the way that int? creates a Nullable<int>. In fact, Nullable<string> is not even a valid type, given Nullable<>'s type constraint of where T : struct.

  • Related