简体   繁体   中英

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM