HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Ternary extension method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
ternarymethodextension

Problem

I created the following HtmlHelper extension method for my Asp.Net MVC Razor views because the ternary syntax sucks when you need to use it intermixed with markup.

Is there a better way to write this and are there any potential type safety issues with it?

public static string GetValueTernary(this HtmlHelper htmlHelper, object a, object b, object valueIfEqual, object valueIfNotEqual)
{
    return a.Equals(b) ? valueIfEqual.ToString() : valueIfNotEqual.ToString();
}


and its usage in a Razor view is like this:

...

Solution

I would change your method to use generics (so that the return value is meaningful) and not call .ToString() internally. This will enable you to use it in more scenarios.

public static T GetValueTernary(this HtmlHelper html, object a, object b, T valueIfEqual, T valueIfNotEqual)
{
    return object.Equals(a, b) ? valueIfEqual : valueIfNotEqual;
}


Now you can use it like this as well and also it will enable you to use HtmlString-s as values.

...


You could also benefit (depends on your actual usage) from not using object for the compared values - by using a generic the compiler will complain if the types of the two are not compatible (for example, you are comparing string to int):

public static TReturn GetValueTernary(this HtmlHelper html, TValue a, TValue b, TReturn valueIfEqual, TReturn valueIfNotEqual)
{
    return object.Equals(a, b) ? valueIfEqual : valueIfNotEqual;
}

Code Snippets

public static T GetValueTernary<T>(this HtmlHelper html, object a, object b, T valueIfEqual, T valueIfNotEqual)
{
    return object.Equals(a, b) ? valueIfEqual : valueIfNotEqual;
}
<div class="@Html.GetValueTernary(Model.UserVoteTypeId, VoteType.UpVote, "us", "u").ToUpper()">...</div>
public static TReturn GetValueTernary<TValue, TReturn>(this HtmlHelper html, TValue a, TValue b, TReturn valueIfEqual, TReturn valueIfNotEqual)
{
    return object.Equals(a, b) ? valueIfEqual : valueIfNotEqual;
}

Context

StackExchange Code Review Q#41982, answer score: 11

Revisions (0)

No revisions yet.