Differentiate between 'out' and 'param' keywords in c# with example.

Asked 25-Aug-2021
Viewed 589 times

0

Differentiate between 'out' and 'param' keywords in c# with example. 


1 Answer


0

Differentiate between 'out' and 'param' keywords in c# with example.

out keyword params keyword
It is not necessary to initialize parameters before pass data at the function call. It is not necessary to initialize parameters before they pass out we can pass multiple values using this keyword.
It is necessary to initialize the value of a parameter before returning the value to the calling method. It is not necessary to initialize the value of a parameter before returning to the calling method, only accessed.
The declaring of parameters through 'out' parameters is useful when a method returns multiple values. it returns a single value.
When out keyword is used the data only passed in unidirectional. When the params keyword is used the data is accessed only.

Example 

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ThreadDemo
{
    class OutAndParamsDemo
    {
        private int CountDigit(long value)
        {
            int count = 0;
            while (value != 0)
            {
                value /= 10;
                count++;
            }
            return count;
        }
        public void PrintNumberOfDigits(params long[] num)
        {
            foreach (long item in num)
            {
                Console.WriteLine($'{item} has {this.CountDigit(item)} digits.');
            }
        }
        public void GetValueByFunction(out int x, out int y)
        {
            x = 0;y = 0;
            x = 100;
        }
        public static void Main(string[] args)
        {
            OutAndParamsDemo outAnd = new OutAndParamsDemo();
            int n, p;
            // call the print number of digits function
            outAnd.PrintNumberOfDigits(751, 125, 485, 452196, 4152, 1450, 10101010101);
            // call the get value by function
            outAnd.GetValueByFunction(out n, out p);
            Console.WriteLine($'N : {n} P : {p}');
        }
    }
}

Output 

Differentiate between out and param keywords in c with example