A method in C# is typically a block of code or instructions within a program that allows the user to reuse the same code, which ultimately saves excessive memory consumption, saves time, and more importantly. This improves the readability of your code.
Therefore, we can say that a method is a collection of statements that perform a specific task and may or may not return a result to the caller. In certain situations, a user may want to run a method, but that method may require some valuable input in order to perform and complete its task. These input values ​​are called “parameters” in computer languages.
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
Named parameters allow you to specify the value of a parameter based on its name rather than its order within the method.
In other words, you are given the opportunity to not remember the parameters according to their order. This concept was introduced in C# 4.0. This makes the program easier to understand when dealing with a large number of parameters within a method. However, note that named parameters always appear after fixed arguments. If you try to specify a fixed argument after a named parameter, the compiler will throw an error.
Example:
// C# program to illustrate the
// concept of the named parameters
using System;
public class CodeConfig {
// 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: "Welcome", s2: "To", s3: "CodeConfig");
}
}
Output:Final string is: Welcome To CodeConfig
Ref Parameters
“ref” is a C# keyword used to pass value types by reference. Alternatively, we can say that changes made to this argument within the method will be reflected in this variable when control returns to the calling method. ref parameters do not pass properties. Ref parameters require the parameter to be initialized before being passed to Ref. Passing values ​​through “ref” parameters 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 CodeConfig {
// 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 CodeConfig{
// 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 = 50;
num += num;
}
}
Output: The sum of the value is: 100
Default or Optional Parameters
As the name suggests, optional parameters are optional rather than required parameters. It is useful to exclude arguments for some parameters. Or you can say that with optional parameters you don’t have to pass all the parameters in the method. This concept was introduced in C# 4.0. Each optional parameter has a default value that is part of its definition. If you do not pass an argument for an optional parameter, the default value is used. Optional parameters are always defined at the end of the parameter list. That is, the last parameter of a method, constructor, etc. is an optional parameter.
Example:
// C# program to illustrate the
// concept of optional parameters
using System;
class CodeConfig {
// 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");
}
}
Dynamic Parameters
C# 4.0 introduces a new parameter type called dynamic parameters.
Here the parameters are passed dynamically. This means that the compiler does not check the type of dynamic type variables at compile time, but instead retrieves the type at run time. Dynamic type variables are created using the dynamic keyword.
Example:
// C# program to illustrate the concept
// of the dynamic parameters
using System;
class CodeConfig{
// 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(40);
}
}
Output: 1600
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 CodeConfig
{
// Main Method
static public void Main()
{
// The value of the parameter
// is already assigned
string str1 = "Code";
string str2 = "Config";
string res = addstr(str1, str2);
Console.WriteLine(res);
}
public static string addstr(string s1, string s2)
{
return s1 + s2;
}
}
Output: CodeConfig
Params
This is useful when the programmer has no prior knowledge of the number of parameters to use. Parameters allow you to pass any number of arguments. Only one params keyword is allowed; no other parameters after the params keyword are allowed in the function declaration. If no arguments are passed, the parameter length is zero.
Example:
// C# program to illustrate params
using System;
namespace Examples {
class CodeConfig
{
// 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(10, 49, 56, 69, 78);
// show result
Console.WriteLine(x);
}
}
}
Output: 147,682,080
I hope you enjoyed reading this post. For more information you can check out Microsoft learn.
For more information you can visit our C# Section for more such posts.