Parameter Modifier (out, ref, params)

Parameter Modifiers are used to control how parameters are passed to the methods. There are three types of parameter modifiers: ref, out and params. If there is no modifier mentioned, it means it is passed value meaning the called method receives a copy of the original data. We cannot define overloaded method if it differs from another method only on out and ref.

out modifier
Output parameters must be assigned by the method being called, hence are passed by reference. We use out keyword to define output parameters.

class Program
{
     static void Main(string[] args)
     {
          int resultOut;
          AddNumbersOut(10, 20, out resultOut);
          Console.WriteLine("Value of result using out parameter: " + resultOut);
     }
     static void AddNumbersOut(int num1, int num2, out int sum)
     {
          sum = num1 + num2;
     }
}

If the called method fails to assign output parameters, a compiler error is raised.

ref modifier
The value is initially assigned by the caller and may be optionally reassigned by the called method. Data is passed by reference. No compiler error is generated if the called method fails to assign a ref parameter.

class Program
{
      static void Main(string[] args)
      {
          int resultRef=0;
          AddNumbersRef(10, 20, ref resultRef);
          Console.WriteLine("Value of result using out parameter: " + resultRef);
      }
      static void AddNumbersRef(int num1, int num2, ref int sum)
      {
          sum = num1 + num2;
      }
}

If caller method fails to assign the ref variable before passing it to the method, a compiler error is generated.

params modifier
This modifier allows you to send in a variable a number of arguments as a single logical parameter. A method can have a single params modifier, and it must be the final parameter of the method. Arguments marked with the params keyword can be processed if the caller sends in a strongly typed array or a comma-delimited list of items. These arguments are of same data type.

To understand this, lets create a method which can take any number of arguments and return the sum of those values.

class Program
{
     static void Main(string[] args)
     {
          int resultParams;
          AddNumbersParams(out resultParams, 10,20,30,40,50);
          Console.WriteLine("Value of result using out parameter: " + resultParams);}
     }
     static void AddNumbersParams(out int sum, params int[] nums)
     {
          sum=0;
          if (nums.Length == 0)
              sum = 0;
          for(int i=0;i<nums.Length;i++)
          {
              sum = sum + nums[i];
          }
     }
}

If you do not declare params as the last parameter, it will raise a compiler error.

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started