2

Consider the below programs. I would like to know why this code behaves in a different way.

This is returning an error during compile time:

void access<T>(T val, bool result){
var getaccess = val is int? & result;
} 

This is not returning any error:

void access<T>(T val, bool result){
var getaccess = val is Nullable<int> & result;
}
Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
GANESH GANI
  • 101
  • 11
  • provide the compile time error (code/description/reference) – Brett Caswell Jul 17 '17 at 08:47
  • Maybe this will help you [Nullable vs. int? - Is there any difference?](https://stackoverflow.com/questions/4028830/nullableint-vs-int-is-there-any-difference). Have a look at the answer from qqbenq – Mighty Badaboom Jul 17 '17 at 08:48
  • 4
    Possible duplicate of [Nullable vs. int? - Is there any difference?](https://stackoverflow.com/questions/4028830/nullableint-vs-int-is-there-any-difference) – Owen Pauling Jul 17 '17 at 08:49
  • I think it the compiler is expecting the `?` to be part of a ternary expression. If you put parenthesis around it, it works: `(val is int?) & result;` – Dennis_E Jul 17 '17 at 08:51
  • I agree, it is a duplicate.. but only because that question is ambiguous and open-ended. – Brett Caswell Jul 17 '17 at 08:51

1 Answers1

4

This is simply because ? and & are overloaded and can also indicate a conditional operator and "address of" respectively. The compiler needs to know what you mean. This fixes it:

var getaccess = (val is int?) & result;

The compiler message isn't entirely clear, but gives us the clues:

CS0214  Pointers and fixed size buffers may only be used in an unsafe 

(which is from the & result)

CS1003  Syntax error, ':' expected

(which is from the ?)

and:

CS1525  Invalid expression term ';'

(which is also from the ? because it expects a : {value if false} expression before the next semicolon)

Basically, without the parentheses it thinks you mean:

var getaccess = (val is int) ? (&result)

(with a missing expression for what to do if val is not an int)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900