Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

A Generic Ternary Operator for value types and parameterless method

3.50/5 (2 votes)
25 Jun 2011CPOL2 min read 19.8K  
A Generic Ternary Operator for value types and parameterless method
Generic Ternary Operation

Ternary operator is handy to write conditional operation for example ( Condition )? If_condition_true(first_expression) : If_condition_false(second_expression). So if we have a condition block with 10 lines of code, first_expression and second_expression have a few extra lines of code, then use of ternary operator will be bit different. To do this, we can introduce a method block with return type of bool for condition, a method for first_expression and also a method for second_expression. Both first_expression and second_expression method have to be of the same return type.

So keeping all the above stuff in mind, I was thinking it would be really handy if we have a kind of extension method which will give us an option to use ternary operation on the condition block. For example, (Condition Block).TernaryOp<type>(ifConditionTrue, ifConditionFalse</type>). As a result of this, I created few extension methods for Ternary operator and also made it generic. The reason I made it generic to give constraints on the input parameters and return type.
Enough discussion... let's see the code. The following GenericTernaryOperatorExtensions class defines a few extension methods:

C#
public static class GenericTernaryOperatorExtensions
{
    public static void TernaryOp(this Func<bool> condition, Action ifConditionTrue, Action ifConditionFalse)
    {
       (condition() ? ifConditionTrue : ifConditionFalse)();
    }

    public static TResult TernaryOp<TResult>(this Func<bool> condition, TResult ifConditionTrue, TResult ifConditionFalse)
    {
        return condition() ? ifConditionTrue : ifConditionFalse;
    }

    public static TResult TernaryOp<TResult>(this Func<bool> condition, Tuple<TResult, TResult> items)
    {
        return condition() ? items.Item1 : items.Item2;
    }
 }


For the above code block, we can see that there are three extension methods:

TernaryOp(this Func<bool> condition, Action ifConditionTrue, Action ifConditionFalse)

This extension will work on Func<bool></bool> with two parameterless methods as input and also those methods must not return anything.

TResult TernaryOp<TResult>(this Func<bool> condition, TResult ifConditionTrue, TResult ifConditionFalse)


Same like the first one, except two parameters it will take will be values. And types of those have to be defined when we call TernaryOp.

TResult TernaryOp<TResult>(this Func<bool> condition, Tuple<TResult, TResult> items)

is the same as second one above, but it will take a tuple of items to do the operation.

The usage of those above extension methods are below:

C#
static void Main(string[] args)
{
      Console.WriteLine("{0}-{1}-{2}-{3}", new object[]
      {
         InnerCondition().TernaryOp<int>(5, 6),
         InnerCondition().TernaryOp<string>("5", "6"),
         InnerCondition().TernaryOp<int>(Sum(3, 4), Sum(6)),
         InnerCondition().TernaryOp<int>(Tuple.Create<int, int>(Sum(3, 3), Sum(4)))
      });

     Console.WriteLine("\nParameterless method call using ternary op:\n");
     InnerCondition().TernaryOp(MethodIfTrue, MethodIfFalse);
     ((Func<bool>)(() => { return true; })).TernaryOp(MethodIfTrue, MethodIfFalse);
}


and related code:

C#
public static void MethodIfTrue()
{
     Console.WriteLine("Generic Ternary Operator for true.");
}

public static void MethodIfFalse()
{
     Console.WriteLine("Generic Ternary Operator for false.");
}

public static int Sum(int a)
{
    int b = 10;
    return a + b;
}

public static int Sum(int a, int b)
{
    return a + b;
}

public static Func<bool> InnerCondition()
{
    return (() => { return DateTime.Now.Ticks % 2 == 0; });
}


The InnerCondition method will return an Anonymous Method which contains the conditional expression for the ternary operator.

Source code of Ternary operation could be found in Generic design Pattern section of this Project.[^].

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)