We can simplify if..then..else statement(or can write shorthand
expression) with the help of Ternary Operators. The ternary operator tests a
condition. It compares two values. It produces a third value that depends on
the result of the comparison. This can be accomplished with if-statements or
other constructs. But the ternary operator provides an elegant and equivalent
syntax form.
For example here is function which used to take one object
as parameter and return object’s value as String if it’s not null, else it’ll
return empty string.
private
String GetValueFromObject(object value)
{
if
(value != null)
{
return
value.ToString();
}
else
{
return
String.Empty;
}
}
|
We can write whole if else condition in line as:
private
String GetValueFromObject(object value)
{
return
value != null ? value.ToString() : String.Empty;
}
|
Comments
Post a Comment