The conditional operator
var result = x ? y : z;
can be seen as a shortcut for something like
T result;
if (x)
result = y;
else
result = z;
with T
being the type of both y
and z
. This makes clear that y
and z
must resolve to values (and not statements) of the same type so the entire statement has a consistent type.
This also makes clear that you can not simply use any method call for y
or z
, but only such method calls that result in values of the same type.
So while it is ok to write
var value = condition ? func1() : func2(someValue);
as long as func1
and func2
are methods returning values of the same type, it is not ok to write
var value = condition ? return : null;
return
is not a value and you may not use return
as one of the operands in the conditional operator. You may not even do this:
var value = condition ? return true : false;
You could even do something like this:
if ((File.Exists(dest) ? CalcFileSize(dest) : 0) > 0)
{
// Do something if the file exists and it has content
}
It's far easier (and correct) in this case to simply use the good old if
:
if (File.Exists(dest))
return;
File.Copy(template, dest);