November 4, 2012
?: Operator return void
Question by Artur Keyan
I want to use the ?:
operator intstead of if else
e.g.
var directory = new DirectoryInfo(path);
if (!directory.Exist())
{
directory.Create();
}
else
{
// do nothing
}
I tried to use ?:
like this:
var directory = new DirectoryInfo(path);
!directory.Exist() ? directory.Create() : void;
but it says “Invalid expression term ‘void’“, null also isn’t working.
Can anyone tell me a solution? Thanks.
Answer by Starx
Ternary operator are not designed to replace if/else
They are to simplify assignment and declaration. It should be able to assign the result the statement to something like variable or function. There major use are in assignment or reading.
Something like
var status = !directory.Exist() ? directory.Create() : false;
The correct solution would be to stick to native if
condition. The following is enough:
var directory = new DirectoryInfo(path);
if (!directory.Exist())
{
directory.Create();
}