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.

sebastian.roibu
  • 2,579
  • 7
  • 37
  • 59
  • 2
    `this T?` makes no sense at all, as a `class` is nullable per definition. – MakePeaceGreatAgain Sep 19 '19 at 14:50
  • 4
    `where T : struct`, you mean. – Jeroen Mostert Sep 19 '19 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. – Tim Schmelter Sep 19 '19 at 14:53
  • Read Eric Lippert's [Vexing exceptions](https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/) to find out why this is a bad idea in the first place. – Zohar Peled Sep 19 '19 at 14:53
  • You can't write "this T?" where T is class because nullable isn't allowed for object that use extension method. It is like you want to write: null.DoSomething(). T can't be nullable said the compiler. You only can contrainst on where T is struct as mention Viktor Arsanov. –  Sep 19 '19 at 14:56
  • 1
    Possible duplicate of [Creating a nullable extension method ,how do you do it?](https://stackoverflow.com/questions/6561697/creating-a-nullablet-extension-method-how-do-you-do-it) – Sinatr Sep 19 '19 at 14:59
  • Thanks for the comments. Learned a lot from them. – sebastian.roibu Sep 19 '19 at 16:18

1 Answers1

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

Viktor Arsanov
  • 1,285
  • 1
  • 9
  • 17