Thursday, August 9, 2018

Improvements in out paramenters in C#7.0

There is a slight improvement in calling a method using out parameter in C# 7.0. Instead of declaring variables separately outside we can declare them while calling method itself.

In the two examples below which is colored, you could find the way of using out parameters. 
  class Sample
    {
        public void Cals(int val1, int val2, out int val3, out int val4)
        {
            val3 = val1 + val2;
            val4 = val1 * val2;
        }
        static void Main()
        {
            int m = 100, n = 50;
            Sample S = new Sample();
            int x, y;
            S.Cals(m, n, out x, out y);
            Console.WriteLine("x = "+x + "and y = " + y);
            Console.Read();
        }
    }
  Output:
  x = 150 and y = 5000

    class Sample
    {
        public void Cals(int val1, int val2, out int val3, out int val4)
        {
            val3 = val1 + val2;
            val4 = val1 * val2;
        }
        static void Main()
        {
            int m = 100, n = 50;
            Sample S = new Sample();
            S.Cals(m, n, out int x, out int y);
            Console.WriteLine(x + " " + y);
            Console.Read();
        }
    }
  Output:
  x = 150 and y = 5000

No comments:

Post a Comment