Ternary extension method 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:

&lt;div class="@Html.GetValueTernary(Model.UserVoteTypeId, VoteType.UpVote, "us", "u")"&gt;...&lt;/div&gt;
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&lt;T&gt;(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.

&lt;div class="@Html.GetValueTernary(Model.UserVoteTypeId, VoteType.UpVote, "us", "u").ToUpper()"&gt;...&lt;/div&gt;


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&lt;TValue, TReturn&gt;(this HtmlHelper html, TValue a, TValue b, TReturn valueIfEqual, TReturn valueIfNotEqual)
{
    return object.Equals(a, b) ? valueIfEqual : valueIfNotEqual;
}