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();
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!