Reputation: 33
I'm currently working on enabling the nullable option on one of our company projects, and I'm not sure how to handle the following situation.
public class MyCollection<T>
{
private T[] myArray;
public T this[int i]
{
get => myArray[i];
set => myArray[i] = value;
}
}
If T is a reference type, I want null to be a valid value. But in case of a value type, I don't want Nullable<T>
to be involved, keep the type as is.
I tried playing with annotations, but in the end if value
can be null in the setter, I'm forced to declare myArray
as a T?[]
.
public class MyCollection<T>
{
private T[];
[AllowNull]
public T this[int i]
{
[return: MaybeNull]
get => myArray[i];
set => myArray[i] = value; // Possibly null
}
}
So I guess my questions are :
myArray
a T?[]
, will the compiler enforce the use of Nullable<T>
for value types ?Upvotes: 3
Views: 427
Reputation: 310997
In C# 9 you can apply ?
to an "unconstrained generic type" and it won't produce Nullable<T>
if T
is a struct
.
So your example becomes:
public class MyCollection<T>
{
private T?[] myArray;
public T? this[int i]
{
get => myArray[i];
set => myArray[i] = value;
}
}
The attributes work too, but are less elegant.
Upvotes: 3