In C# 8 with nullable enabled, is there a way to identify a nullable reference type for generic type?
For nullable value type, there is a section dedicated to it. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#how-to-identify-a-nullable-value-type
We are trying to do optional null check according to the generic type
#nullable enable
public static Result<T> Create<T>(T value)
{
if (!typeof(T).IsNullable() && value is null)
throw new ArgumentNullException(nameof(value));
// Do something
}
public static bool IsNullable(this Type type)
{
// If type is SomeClass, return false
// If type is SomeClass?, return true
// If type is SomeEnum, return false
// If type is SomeEnum?, return true
// If type is string, return false
// If type is string?, return true
// If type is int, return false
// If type is int?, return true
// etc
}
So the following will throw ArgumentNullException
when T
is not nullable
But allow value to be null with no exception when T
is nullable, e.g.
Create<Anything>(null); // throw ArgumentNullException
Create<Anything?>(null); // No excception
where T : notnull
. I want theCreate<T>
method to throwArgumentNullException
according to ifT
is nullable – Openhanded