Phiter
Phiter

Reputation: 14982

Is there a syntatic sugar for ternary when you want only one outcome?

In C#, many times I want to retrieve a string based on a expression. Most of the times I do this in the views.

So, for example, if I want to print "Complete" based on a boolean isComplete, I need to do this:

<span class="badge">@(isComplete? "Complete" : "")</span>

Is there any option in the language that would shorten this syntax, so I don't need to also have the empty string option?

Something like

<span class="badge">@(isComplete => "Complete")</span>

There are some ways to do this yourself, like a function that would receive a string and a boolean, and return null or empty if the boolean is false, but maybe it already exists in the language.

Upvotes: 0

Views: 82

Answers (2)

Slai
Slai

Reputation: 22876

Not yet, but here are few alternatives:

<span class="badge">@isComplete.Complete()</span> - extension method

<span class="badge">@Complete(isComplete)</span> - method

<span class="badge">@(Complete)isComplete</span> - custom type with explicit operator

<span class="badge">@isComplete</span> - custom boolean type with override ToString

Upvotes: 0

Mike Nakis
Mike Nakis

Reputation: 62082

You can simply declare a function like this:

public String GetTextOrEmpty( bool control, String text )
{
    return control? text : "";
}

And then invoke it like this:

<span class="badge">@(GetTextOrEmpty( isComplete, "Complete" ))</span>

Upvotes: 1

Related Questions