开发者

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 开发者_如何学Celse statement like that.

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


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.


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜