Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: throw invalid expression compilation

Tags:

c#

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?

like image 664
Jordi Avatar asked Nov 07 '17 11:11

Jordi


2 Answers

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;
like image 101
Gilad Green Avatar answered Sep 20 '22 14:09

Gilad Green


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

like image 29
Eleanor Holley Avatar answered Sep 19 '22 14:09

Eleanor Holley