In C# it's trivial to determine whether a value type is nullable. Specifically, you can obtain this information from the Type
itself; for example:
public static bool IsNullable(this Type type) =>
type.IsValueType && Nullable.GetUnderlyingType(type) is not null;
As I understand, it's possible to obtain nullability information for nullable reference types via NullableAttribute
or NullableContextAttribute
, but it would appear that this has to be obtained from MemberInfo
, rather than from the Type
.
Is this understanding correct, or is there a workaround to obtain nullability information for nullable reference types from a Type
?
string?
is not a different type thanstring
, so there is no way to check if it's a nullable reference type. You can just check it if you have theMemberInfo
– KellbyType
. TheMemberInfo
: is more contextual, so: yup – ScornikType
thatNullableAttribute
andNullableContextAttribute
are introduced. – Rutherfordpublic class Foo? { }
or similar. You create a classFoo
, and then variables / fields / parameters / etc have a type which isFoo
orFoo?
. Therefore, it is not the type itself which is nullable, but the variable / field / parameter which uses that type. Therefore, it makes sense that you can't get nullability information from aType
, because such a thing wouldn't make any sense – ShippeeType
, which is not possible. – Euglena