Ternary operator in C#

By | June 13, 2018

Ternary Operator:  ” ?: ”

Ternary operator means simple if else condition in one statement based on condition.

we can say this is dicision making operator.

Syntax:

var output = Boolean expression ? first value : second value

It three parts,

First part (before ?) includes conditional expression that returns boolean value true or false.

Second part (after ? and before ‘:’ colon) contains a statement which will be returned if the conditional expression in the first part evalutes to true.

The third part includes another statement which will be returned if the conditional expression returns false.

Example:

string strMessage = ""; 
var output = string.IsNullOrEmpty(strMessage) ? "Message is Empty" : strMessage;

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *