C# Method Parameters

C# Method Parameters are generally the block of codes or statements in a program which gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, it provides better readability of the code. So you can say a method is a collection of statements that perform some specific task and may/may not return the result to the caller.

There might be certain situations the user want to execute a method but sometimes that method requires some valuable inputs in order to execute and complete its tasks. These input values are known as Parameters in computer language terms.

C# contains the following types of Method Parameters:

  • Named Parameters
  • Ref Parameters
  • Out Parameters
  • Default or Optional Parameters
  • Dynamic Parameters
  • Value Parameters
  • Params

Named Parameters

Using named parameters, you can specify the value of the parameter according to their names not their order in the method. Or in other words, it provides us a facility to not remember parameters according to their order. This concept is introduced in C# 4.0. It makes your program easier to understand when you are working with a larger number of parameters in your method. But always remember named parameters are always appear after fixed arguments, if you try to provide fixed argument after named parameter, then the compiler will throw an error.

Example:

// C# program to illustrate the 
// concept of the named parameters
using System;
  
public class TAPP {
  
    // addstr contain three parameters
    public static void addstr(string s1, string s2, string s3)
    {
        string result = s1 + s2 + s3;
        Console.WriteLine("Final string is: " + result);
    }
  
    // Main Method
    static public void Main()
    {
        // calling the static method with named 
        // parameters without any order
        addstr(s1: "Tech", s2: "for", s3: "Tech");
                     
    }

Output:

Final string is: TechforTech

Ref Parameters

The ref is a keyword in C# which is used for passing the value types by reference. Or we can say that if any changes made in this argument in the method will reflect in that variable when the control return to the calling method. The ref parameter does not pass the property. In ref parameters, it is necessary that the parameters should initialize before it pass to ref. The passing of value through the ref parameter is useful when the called method also needs to change the value of the passed parameter.

Example:

// C# program to illustrate the
// concept of ref parameter
using System;
  
class TAPP{
  
    // Main Method
    public static void Main()
    {
  
        // Assigning value
        string val = "Dog";
  
        // Pass as a reference parameter
        CompareValue(ref val);
  
        // Display the given value
        Console.WriteLine(val);
    }
  
    static void CompareValue(ref string val1)
    {
        // Compare the value
        if (val1 == "Dog") 
        {
            Console.WriteLine("Matched!");
        }
  
        // Assigning new value
        val1 = "Cat";
    }
}

Output:

Matched!
Cat

Out Parameters

The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property. It is not necessary to initialize parameters before it passes to out. The declaring of parameter throughout parameter is useful when a method returns multiple values.

Example:

// C# program to illustrate the
// concept of out parameter
using System;
  
class TAPP {
  
    // Main method
    static public void Main()
    {
  
        // Creating variable
        // without assigning value
        int num;
  
        // Pass variable num to the method
        // using out keyword
        AddNum(out num);
  
        // Display the value of num
        Console.WriteLine("The sum of"
          + " the value is: {0}",num);
                            
    }
  
    // Method in which out parameter is passed
    // and this method returns the value of
    // the passed parameter
    public static void AddNum(out int num)
    {
        num = 40;
        num += num;
    }
}

Output:

The sum of the value is: 80

Default or Optional Parameters

As the name suggests optional parameters are not compulsory parameters, they are optional. It helps to exclude arguments for some parameters. Or we can say in optional parameters, it is not necessary to pass all the parameters in the method. This concept is introduced in C# 4.0. Here, each and every optional parameter contains a default value which is the part of its definition. If we do not pass any arguments to the optional parameters, then it takes its default value. The optional parameters are always defined at the end of the parameter list. Or in other words, the last parameter of the method, constructor, etc. is the optional parameter.

Example:

// C# program to illustrate the 
// concept of optional parameters 
using System; 
    
class TAPP { 
    
    // This method contains two regular 
    // parameters, i.e. ename and eid
    // And two optional parameters, i.e. 
    // bgrp and dept 
    static public void detail(string ename,  
                               int eid, 
                               string bgrp = "A+", 
                    string dept = "Review-Team") 
    
    { 
        Console.WriteLine("Employee name: {0}", ename); 
        Console.WriteLine("Employee ID: {0}", eid); 
        Console.WriteLine("Blood Group: {0}", bgrp); 
        Console.WriteLine("Department: {0}", dept); 
    } 
    
    // Main Method 
    static public void Main() 
    { 
    
        // Calling the detail method 
        detail("XYZ", 123); 
        detail("ABC", 456, "B-"); 
        detail("DEF", 789, "B+", 
           "Software Developer"); 
    } 
}

Output:

Employee name: XYZ
Employee ID: 123
Blood Group: A+
Department: Review-Team
Employee name: ABC
Employee ID: 456
Blood Group: B-
Department: Review-Team
Employee name: DEF
Employee ID: 789
Blood Group: B+
Department: Software Developer

Dynamic Parameters

In C# 4.0, a new type of parameters is introduced that is known as a dynamic parameter. Here the parameters pass dynamically means the compiler does not check the type of the dynamic type variable at compile-time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using a dynamic keyword.

Example:

// C# program to illustrate the concept 
// of the dynamic parameters
using System;
  
class TAPP {
  
    // Method which contains dynamic parameter
    public static void mulval(dynamic val)
    {
        val *= val;
        Console.WriteLine(val);
    }
  
    // Main method
    static public void Main()
    {
  
        // Calling mulval method
        mulval(30);
    }
}

Output:

900

Value Parameters

It is a normal value parameter in a method or you can say the passing of value types by value. So when the variables are passed as value type they contain the data or value, not any reference. If you will make any changes in the value type parameter then it will not reflect the original value stored as an argument.

Example:

// C# program to illustrate value parameters
using System;
  
public class TAPP {
  
    // Main Method
    static public void Main()
    {
  
        // The value of the parameter
        // is already assigned
        string str1 = "Tech";
        string str2 = "tech";
        string res = addstr(str1, str2);
        Console.WriteLine(res);
    }
  
    public static string addstr(string s1, string s2)
    {
        return s1 + s2;
    }
}

Output:

Techtech

Params

It is useful when the programmer doesn’t have any prior knowledge about the number of parameters to be used. By using params you are allowed to pass any variable number of arguments. Only one params keyword is allowed and no additional Params will be allowed in function declaration after a params keyword. The length of params will be zero if no arguments will be passed.

Example:

// C# program to illustrate params
using System;
namespace Examples {
  
class Tech {
  
    // function containing params parameters
    public static int mulval(params int[] num)
    {
        int res = 1;
  
        // foreach loop
        foreach(int j in num)
        {
            res *= j;
        }
        return res;
    }
  
    static void Main(string[] args)
    {
  
        // Calling mulval method
        int x = mulval(20, 49, 56, 69, 78);
  
        // show result
        Console.WriteLine(x);
    }
}
}

Output:

295364160

Chockalingam