Rafael Herscovici
Rafael Herscovici

Reputation: 17094

How is this " IF ELSE " statement called?

i sometimes use this kind of if in my code:

!Value == null ? DoSomething : DoSomethingElse;

and i was wondering what is the proper name for an if else statement like that.

also, i wonder if there can only be a if part, without the else in the same structure.

Upvotes: 0

Views: 360

Answers (3)

dougajmcdonald
dougajmcdonald

Reputation: 20037

To answer your second question:

also, i wonder if there can only be a if part, without the else in the same structure

The answer is 'kind of', if you want to check for a null, which is called a null coalesce. The syntax is similar and goes like this:

myVariable = aPossiblyNullValue ?? ReturnThisIfNull;

What this does is return the left hand side if the value is not null and if it is null, return the right.

Upvotes: 2

Ray
Ray

Reputation: 46585

It's called a conditional operator. It is a ternary operator (and the only one), but that's not what it's called.

You can't use it as you can use an if statement. You can only use it where you need it to return one of two values. The two values need to be the same type, or an implicit conversion needs to exist between them.

Upvotes: 9

kaps
kaps

Reputation: 478

Its' called ternary operator and it works like...

!Value == null ? DoSomething : DoSomethingElse;

If value is not null (as you have added !) then do something (DoSomething will be called. Else, (means if the codition fails), then do something else (DoSomethingElse will be called).

Upvotes: 0

Related Questions