Reputation: 2859
I want to write a generic extension method that throws an error if there is no value. SO I want something like:
public static T GetValueOrThrow(this T? candidate) where T : class
{
if (candidate.HasValue == false)
{
throw new ArgumentNullException(nameof(candidate));
}
return candidate.Value;
}
Any idea if this works? What am I missing?
I also come up with:
public static T GetValueOrThrow<T>(this T? candidate) where T : class
{
if (candidate.HasValue == false)
{
throw new ArgumentNullException(nameof(candidate));
}
return candidate.Value;
}
Now C# complains about the candidate: The type T must be a non nullable value type in order to use it as parameter T in the generic type or method Nullable
This is not related to comparing.
Upvotes: 3
Views: 1718
Reputation: 1583
public static T GetValueOrThrow<T>(this Nullable<T> candidate) where T : struct // can be this T? as well, but I think with explicit type is easier to understand
{
if (candidate.HasValue == false)
{
throw new ArgumentNullException(nameof(candidate));
}
return candidate.Value;
}
where T : class
constrains to reference types, which can be null, but HasValue is property of Nullable type(which is value type as well as T).
Upvotes: 8