sebastian.roibu
sebastian.roibu

Reputation: 2859

Nullable generic extension method

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;
        }
  1. C# is not recognizing the T: The type or namespace name "T" cannot be found
  2. C# is not recognizing where : Constraints are not allowed on non generic declarations

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

Answers (1)

Viktor Arsanov
Viktor Arsanov

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

Related Questions