If have the following statement:
return this.revision.HasValue ? this.revision : throw new InvalidOperationException();
I thought it would compile as the throw is breaking the normal flow and it shouldn't be a problem to not return a value but it does not build.
Is there a way to put right this statement or why is this not allowed?
Thanks.
EDIT: this.revision is int? and the method returns int.
EDIT 2: if I have this method
public int Test()
{
throw new Exception();
}
The compiler does not complain about not returning a value, I expected the same thing from an inline if ... at least we know that can be done as it's already done in methods.
As inline if-else statements are logical statements that offer a single line that preserves code quality by replacing the multiple lines of if-else code. Inline if-else statements should be used with the expressions and their execution based on the evaluation conditions.
The most common and widely used statement is the if statement. It will compute if a statement is true or false. If it's true, it will execute the code. If it's false, it won't execute the code.
An inline PERFORM is an imperative statement that is executed in the normal flow of a program; an out-of-line PERFORM entails a branch to a named paragraph and an implicit return from that paragraph.
Syntax: result = condition ? value1 : value2; If condition is true then value1 will be assigned to result variable and if wrong then value2 will be assigned.
Converting comment to an answer:
From MSDN:
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
?: Operator
As int?
cannot be converted to an exception, and throw is not an expression, hence the error within your code.
I suppose the problem is in the fact that this.revision is a nullable type and InvalidOperationException() is a SystemException. You cannot have two different types in an if statement like:
return (a>b)? DateTime.Now : 2;
Please look here: http://msdn.microsoft.com/en-us/library/vstudio/ty67wk28.aspx
condition ? first_expression : second_expression;
The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
It's because in a ternary expression, the latter two expressions act as a substitute to each other and their return value needs to be of same type or implicitly convertible to type of the variable being assigned.
Clearly, an Exception
has different type than an int
.
MSDN:
If condition is false, second_expression is evaluated and becomes the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With