Saturday 13 October 2018

How to create named tuples in c#

In this post we are going to see how to use the named tuples in C#, Previously when you use the Tuple it will result in showing the values are like Item1, Item2 etc, instead of resemble Item1 and Item2 if we want to name the items, we can do that using the named tuple.


Syntax for named tuple declaration:
(string operation, int result) operationResult;

Let we see a sample like calculator.

public interface ICalculator
    {
       (string operation, int result) DoOperation(string operation, int a, int b);

    }




    public class Calculator:ICalculator
    {
        public (string operation,int result) DoOperation(string operation,int a,int b)
        {
            (string operation, int result) operationResult;
            int c = 0;
            switch (operation)
            {
                case "add":
                    c = a + b;
                    break;
                case "sub":
                    c = a - b;
                    break;
                case "mul":
                    c = a * b;
                    break;
                default:
                    c = a + b;
                    break;
            }
            operationResult =(operation, c);
            return operationResult;
        }
    }

When you see return type of the method DoOperation, it is named tuple

public class CalMachine
    {
        private ICalculator calc;

        public CalMachine():this(new Calculator())
        {

        }

        public CalMachine(ICalculator obj)
        {
            this.calc = obj;
        }

        public (string operation, int result) Operate(string operationType, int a , int b)
        {
            return calc.DoOperation(operationType, a, b);
        }

    }




Main Program

CalMachine cmachine = new CalMachine();
var aresult = cmachine.Operate("add", 1, 2);
Console.WriteLine($"Operation: {aresult.operation}, Result: {aresult.result}");

When you see the main program in the console writeline we are accessing the value from named Tuple based on variable name;

From this post you can see how to create the named Tuples in C#