13

I'm using this code in order to check queryable value:

visitor.Queryable = queryable ?? throw new Exception("error message");

I'm getting a compilation error:

error CS1525: Invalid expression term 'throw'

I'm using 4.5.2 .net framework. Any ideas?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • 2
    [Click](https://stackoverflow.com/q/1762772/1997232). – Sinatr Nov 07 '17 at 11:06
  • It will be useful to also mention in what VS and C# you are working with – Gilad Green Nov 07 '17 at 11:13
  • 1
    `throw` doesn't return a value, which on compilers older than C#7 is not supported with `??` – Rufus L Nov 07 '17 at 11:17
  • @RufusL: That doesn't matter; this is valid C# 7 code, but won't work with other versions. – Jon Skeet Nov 07 '17 at 11:17
  • The version of the framework you're targeting doesn't matter. The version of the compiler you're using very much does. If you're using a C# 7 compiler, this should be fine. If you're using C# 6 or earlier, it won't be. – Jon Skeet Nov 07 '17 at 11:18

2 Answers2

25

This feature is only available post C# 7.0. See under Throw exception of What's New in C# 7.0.

If you are using an older VS and want to enable C# 7 features: Have a look at How to use c#7 with Visual Studio 2015? if not in VS 2017.


If you are working with a previous version of the C# compiler, as you must be due to the error then you cannot use the ?? operator this way as the throw does not return a right operand value. As the C# Docs say:

It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

The pattern is like this:

var result = someObject ?? valueToAssignIfWasNull;

To solve it write instead:

if(queryable == null)
{
    throw new Exception("error message");
}
visitor.Queryable = queryable;
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
1

I upvoted the accepted, but I'll also put forward a workaround:

private Queryable NullAlternative()
{
    throw new ArgumentNullException("Null Queryable not supported at this time.");
}

Then, elsewhere, you can say

visitor.Queryable = queryable ?? NullAlternative();

This is nice if you can't upgrade to VS2017 but don't want to lose the slick conditional syntax, and it has the added benefit of leaving it open to some kind of null-object pattern in the future (such as initializing an empty queryable).

Eleanor Holley
  • 691
  • 1
  • 7
  • 27