3

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.

7
  • 2
    this T? makes no sense at all, as a class is nullable per definition. Commented Sep 19, 2019 at 14:50
  • 4
    where T : struct, you mean. Commented Sep 19, 2019 at 14:50
  • 2
    Why you want that extension at all? It's the default behavior, just use candidate.Value and be excited about the incoming error if there is no value. Commented Sep 19, 2019 at 14:53
  • Read Eric Lippert's Vexing exceptions to find out why this is a bad idea in the first place. Commented Sep 19, 2019 at 14:53
  • 1
    Possible duplicate of Creating a nullable<T> extension method ,how do you do it? Commented Sep 19, 2019 at 14:59

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.