Thursday, April 12, 2012

How to use conditional operator(?:) in c# in a string?

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.

The condition must evaluate to true or false. If condition is truefirst_expression is evaluated and becomes the result. If condition is falsesecond_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
This is what MSDN says. :)
Now: it might help you to know how to use conditional operator when generate a string. I will give you a simple method which receives a input parameter and according to that will generate a link.


public string GenerateLink(string Option)
    {
        string Response = "";
       Response = "<a href=\"YourPage.aspx?option=" + ((Option == "holiday") ? "goHoliday" : "goAndWork").ToString() + "\">Click</a>";
        return Response;
    }

So, don't hesitate to use conditional operator whenever you are in need of it.
Have a nice day.

No comments:

Post a Comment