-1

I'm somewhat new to C#, an someone explain to me the second ViewBag line?

public ActionResult Index(string sortOrder)
{
   ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
   ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
.....
}

This is for a sort order from a tutorial and it works, the first line I get, but I have no idea how the second line works in conjunction.

Thanks


EDIT: My question wasn't about the ternary statement, I thought the sortOrder was also being reassigned instead of just the ViewBag.DateSortParm, which would have caused an issue, but that is not the case, I was just blinded for some reason.

Mankind1023
  • 7,198
  • 16
  • 56
  • 86
  • 2
    It's the [same operator](https://msdn.microsoft.com/en-us/library/ty67wk28.aspx) as the first line - which part don't you understand? – D Stanley Jul 13 '15 at 20:01
  • It is the [Conditional (Ternary) Operator](https://msdn.microsoft.com/en-us/library/zakwfxx4(v=vs.90).aspx). – Uwe Keim Jul 13 '15 at 20:02

3 Answers3

2

It's a ternary if statement. If the sortOrder is equal to "Date" then DateSortParm is assigned the value "date_desc", otherwise it is assigned the value "Date"

JP.
  • 5,536
  • 7
  • 58
  • 100
2

It is called the ternary operator

ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

is the equivalent of:

if(sortOrder == "Date")
{
    ViewBag.DateSortParm = "date_desc";
}
else
{
    ViewBag.DateSortParm =  "Date";
}

It is great because it is a on-liner, that being said you should not overuse them as it could make code cumbersome and unreadable when conditions are more complex.

sirdank
  • 3,351
  • 3
  • 25
  • 58
meda
  • 45,103
  • 14
  • 92
  • 122
  • sorry for some reason I kept thinking sortOrder is being reassigned in the second statement, which would always end up with it being set to Date if someone clicks any other sort, but only the ViewBag.DateSortParam is being set on the line, my bad. – Mankind1023 Jul 13 '15 at 20:09
  • I see your confusion, sometime people add parethensis to avoid confusion `ViewBag.DateSortParm = (sortOrder == "Date") ? "date_desc" : "Date";` – meda Jul 13 '15 at 20:13
0

It's conditional ternary operator:

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. One common use of the ternary operator is to initialize a variable with the result of the expression. At compile-time, the C# compiler translates the ternary expression into branch statements such as brtrue.

So in your case if the sortorder is "Date" the ViewBag would be date_desc if not it would be Date.
more info.

Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110