2

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.

CodeAngry
  • 12,760
  • 3
  • 50
  • 57
  • Even if it's not achievable for regular Variables, for Class Properties it works. Even for these very types I mentioned, if they are Properties of an object you can find the nullability: https://stackoverflow.com/a/71549957/1451110 in `NullabilityInfo.GenericTypeArguments`. – CodeAngry Jun 10 '22 at 07:38

2 Answers2

2

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.

Nigel
  • 2,961
  • 1
  • 14
  • 32
  • I know `Nullable<>` only works with value types so it doesn't apply to `string`. But I hoped there's some metadata/attributes I'm missing that would advertise the nullability of reference types. – CodeAngry Jun 10 '22 at 07:19
2

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.

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34
  • I assumed it's like this. Thanks for the sharplab.io hint! Used it several times when I needed to emit some IL but didn't think to use it to check this. – CodeAngry Jun 10 '22 at 07:23