Click here to Skip to main content
Click here to Skip to main content

Tagged as

A Generic Ternary Operator for value types and parameterless method

, 25 Jun 2011
Rate this:
Please Sign up or sign in to vote.
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(ifConditionTrue, ifConditionFalse). 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:
 
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 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:
 
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:
 
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)

Share

About the Author

Mohammad A Rahman
Software Developer
Australia Australia
Designer and Architect.
Author of the Expert C# 5.0: with the .NET 4.5 Framework book

Comments and Discussions

 
QuestionInteresting, but why? Pinmembernetindustries27-Jun-11 13:18 
AnswerRe: Interesting, but why? PinmemberMohammad A Rahman27-Jun-11 16:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140902.1 | Last Updated 26 Jun 2011
Article Copyright 2011 by Mohammad A Rahman
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid