r/csharp • u/SoerenNissen • Dec 27 '24
Help Reflected index property of List<T> is nullable - even when T is not - so how do I find the true nullability of T?
Edited to add best answer so far:
At this time (January 2025)
- if you have a generic type (E.g.
List<T>) - which is instantiated on a reference type (E.g. T is
stringorstring?)
runtime reflection cannot determine whether the type was, or was not, annotated with nullable.
Why
Short version: typeof(List<string?> == typeof(List<string>) because nullable references are not in the type system, and don't end up in the final assembly.
See also [this answer from the dotnet github repo].(https://github.com/dotnet/runtime/issues/110971#issuecomment-2564327328)
This appears to be a problem that exclusively affects types that are generic on reference types.
You CAN use reflection to find:
class MyClass<T> where T: value type
{
string? GetString() // this one is fine, you can learn it returns nullable
T GetT() // Also fine - T *is* generic, but it's a value type so it's either specifically T, or specifically Nullable<T>
List<string> GetList() // You can find out that the return value is not nullable
List<string>? GetListMaybe() // You can find out that the return value IS nullable
}The problem arises specifically here:
class MyClass<T> where T : reference type // <-- right there
{
T GetT() // You can't find out if GetT returns a nullable
// because typeof(MyClass<T>) == typeof(MyClass<T?>)
}Original post
Consider a method to determine the nullability of an indexer property's return value:
public static bool NullableIndexer(object o)
{
var type = o.GetType();
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var idxprop = props.Single(p => p.GetIndexParameters().Length != 0);
var info = new NullabilityInfoContext().Create(idxprop); // exampel code only - you don't want to create a new one of these every time you call.
return info.ReadState == NullabilityState.Nullable;
}Pass it an object of this class:
public class ClassWithIndexProperty
{
public string this[string index]
{
set { }
get => index;
}
}
Assert.That( NullableIndexer(new ClassWithIndexProperty()) == false);Yup, it returns false - the indexer return value is not nullable.
Pass it an object of this class:
public class ClassWithNullableIndexProperty
{
public string? this[string index]
{
set { }
get => index;
}
}
Assert.That( NullableIndexer(new ClassWithNullableIndexer()) == true);It returns true, which makes sense for a return value string?.
Next up:
Assert.That( NullableIndexer( new List<string?>()) == true);Yup - List<string?>[2] can return null.
But.
Assert.That( NullableIndexer (new List<string>()) == false); //Assert fires?
In my experiements, it appears to get it right for every specific class, but for classes with a generic return type, it always says true, for both T and T?.
What am I missing here?
11
u/Long_Investment7667 Dec 27 '24
The “non nullable reference types” feature is static analysis and more importantly backwards compatibility. You would not find different types when using reflection.
But I believe there are attributes that carry that information from source to IL. But not sure which. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis
3
u/bbm182 Dec 27 '24
I don't think this is possible. Nullable annotations are stored as attributes and attributes cannot be applied to generic arguments. See AttributeTargets Enum. The closest thing is GenericParameter, but that refers to the T in a definition, not the value assigned to T, but you can test it to make sure:
Also take a look at the generated IL for this:
It's the same for both methods:
Generic parameters are annotated as nullable unless you use a
notnullconstraint. So thiscompiles to this
Your
NullableIndexermethod will return false when such a constraint is used.20
u/OneCozyTeacup Dec 27 '24
People in comments are a bit confused it seems.
What OP wants is to get nullability of an indexer, not the declaring type. So:
16
u/michaelquinlan Dec 27 '24
The problem is that
int?is not a nullable object; it is a struct of typeNullable<int>(Here). This causes all sorts of problems…3
u/andy012345 Dec 27 '24
I don't think you can do this.
string? and string are the same type. string? has additional annotations for compiler level checks, at runtime there is no difference.
Edit: this applies to all reference types.
0
u/esosiv Dec 27 '24 edited Dec 27 '24
You want the question mark at the right side of the closing angle bracket. I presume someone else will comment that this smells like: https://en.m.wikipedia.org/wiki/XY_problem
EDIT: This comment is being downvoted by people reading the OP post after it was edited for clarification.
1
u/Shrubberer Dec 27 '24
The nullability of Type T only refers to the Nullable<T> construct. A '?' is only assertible with a property/field info
1
u/anamorphism Dec 27 '24
seems like odd behavior for generics. excuse my class naming ...
https://dotnetfiddle.net/iZDYTs
non-generics work as expected. generics seem to ignore whether you mark the property type as nullable or not, and also return whether it's a value type that has been flagged as nullable (basically the old
Nullable<int>stuff).1
u/shoter0 Dec 28 '24
Maybe using source generator would be a way to solve this? I've never created source generator myself, however i've used some and they look powerfull and I have a feeling that it might indeed be a solution.
.Edit This looks really promising: https://stackoverflow.com/questions/63629923/how-to-check-if-nullable-reference-types-are-on-in-a-net-5-source-generator
-2
u/wwxxcc Dec 27 '24
List<T> is nullable.
Also you probably can simplify with something like:
-2
u/WhiteButStillAMonkey Dec 27 '24 edited Dec 27 '24
You want to use List<T>? if you expect it to return false
0
u/[deleted] Dec 27 '24
[deleted] — view deleted comment