articles

Home / DeveloperSection / Articles / Types of parameter in C#

Types of parameter in C#

Niraj Kumar Mishra1917 25-Aug-2017
There are 4 different types of parameters a method can have.
1. Value parameters: Creates a copy of the parameter passed, so modifications does not affect each other.
Example:
using System;
classProgram
{
    publicstaticvoid Main()
    {
        int i = 0;
        SimpleMethod(i);
        Console.WriteLine(i);
        Console.ReadKey();
    }
    publicstaticvoid SimpleMethod(int j)
    {
        j = 101;
    }
}
OUTPUT:
Types of parameter in C#

2. Reference Parameters: The ref method parameter keyword on a method parameter causes A method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passed back to the calling method.
Example:
using System;
classProgram
{
   publicstaticvoid Main()   {
     int i = 0;
     SimpleMethod(ref i);
     Console.WriteLine(i);
     Console.ReadKey();
   }
   publicstaticvoid SimpleMethod(refint j)
   {
     j = 101;
   }
}
OUTPUT:
Types of parameter in C#

3. Out Parameters:Use when you want a method to return more than one value.
Example:
using System;
classProgram
{
    publicstaticvoid Main() {      int Total = 0;       int Product = 0;      Calculate(10, 20, out Total, out Product);      Console.WriteLine("Sum={0} && Product={1}",Total,Product);
   Console.ReadKey();  }
    publicstaticvoid Calculate(int FN,int SN,outint Sum,outint Product)   {        Sum = FN + SN;
Product = FN * SN;
}
}

OUTPUT:

Types of parameter in C#


4. Parameter Arrays: the params keyword lets you specify a method parameter that takes a variable number of arguments. You can send a comma-separated list of arguments, or only one params keyword is permitted in a method declaration. 

Example:
using System;
classProgram
{    publicstaticvoid Main()
 {       int[] Numbers = newint[3];
   Numbers[0] = 101;
   Numbers[1] = 102;
   Numbers[2] = 103;
   ParamsMethod();
   //ParamsMethod(Numbers);     //ParamsMethod(1, 2,3, 4, 5);  }
    publicstaticvoid ParamsMethod(paramsint[] Numbers)
 {       Console.WriteLine("There are {0} elements",Numbers.Length);
  foreach (int i in Numbers)
   {
     Console.WriteLine(i);
   }
     Console.ReadKey();
 }
}


OUTPUT:
Types of parameter in C#
If you use ParamsMethod(Numbers); method then output are:

Types of parameter in C#
and again if you are use ParamsMethod( ); method then outpur are:

Types of parameter in C#



Updated 07-Sep-2019

Leave Comment

Comments

Liked By