0% found this document useful (0 votes)
14 views4 pages

C# Method Parameters Explained

The document discusses different types of methods in C# including method overloading, optional parameters, named arguments, params parameters, and passing parameters by value, reference, and out. It provides examples for each concept.

Uploaded by

Zeeshan Firdous
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views4 pages

C# Method Parameters Explained

The document discusses different types of methods in C# including method overloading, optional parameters, named arguments, params parameters, and passing parameters by value, reference, and out. It provides examples for each concept.

Uploaded by

Zeeshan Firdous
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DotNetTrainings – Ms.

NET – C#

Methods

Methods are used to avoid the repeating of code.


Method makes our code more readability.
Once we create a method any no of times we can call that method with different data called as
parameters.
A Method can return only one value. And a method type we need to specify before method name.
 Method Overloading
 Optional Parameters (4.0 feature)
 Named Arguments (4.0 feature)
 params Parameter
 Passing argument by value, ref and out

Method Overloading:
 Methods are overloaded when they have same name and different parameters.

 Parameters must be different either in their data type or in their count.

 Method cannot be overloaded based on Return Type or Parameter names.

 Call to the Overloaded method is resolved at compile time and is done based on data type and
count of arguments passed to the method.

 While resolving the called method, the compiler searches for a direct match of arguments and
parameters. Only if a direct match is not available it would then use nearest match for resolving
the call.
Ex:-
void max(int , int)
void max(int , int, int , int)
void max(int , int , int)
void max(float ,float)

Optional parameters
 Every Optional Parameter must have default value.

 Once a parameter is declared as optional all subsequent parameters in the list also must be
declared as optional

Page 1
DotNetTrainings – [Link] – C#

 While calling the method with optional parameters, we may or may not provide the
value/argument for optional parameters. If it’s not provided the default value assigned to the
parameter will be used.
Ex:-

Named Arguments
 While calling a method we can pass arguments based on parameter names and we don’t have to
then pass them in sequence.

using System;
class Program
{
public static void Main()
{
int res = Add(10, 2);
[Link]([Link]());
string str;
str = Add("Deccan", "soft");
[Link](str);
res = Add(10, 2, 4); //Named Arguments
res = Add(10, 2, d:4);
res = Add(b:2, a:10, d:4);
}
static int Add(int a, int b)
{
return Add(a, b, 0);
}
static int Add(int a, int b, int c=0,int d=0)
{
return a + b + c + d;
}
static string Add(string s1, string s2)
{
return s1 + s2;
}
}

params Parameters:
 Only Parameters which are of type array (of any data type) can be declared as params

 If parameter is declared as params either a reference to the array can be passed as argument, 0
or more individual values can be passed to it.

 Only one parameter of a method can be declared as params parameter.

Page 2
DotNetTrainings – [Link] – C#

 It must be last parameter in the list of parameters for a given method.

 If we have other parameters in the list they must be before the params parameter.
Ex:-

using System;
class Program
{
public static void Main()
{
int res = Add(10, 2);
int[] mar = { 1, 2, 3, 4 };
res = Add(mar);
[Link]([Link]());
res = Add();
res = Add(1, 2, 3, 4, 5);
res = Add(1, 2, 3, 4, 5, 6);
res = Add(1, 2, 3, 4, 5, 6, 7);
[Link]([Link]());
}
static int Add(params int[] ar)
{
int sum = 0;
foreach (int n in ar)
sum += n;
return sum;
}
}

Passing parameters by value, out or reference

using System;
class Program
{
public static void Main()
{
int n1, n2, n3;
n1 = n3 = 10;
Foo(n1, out n2, ref n3);
[Link](n1 + " " + n2 + " " + n3);
}
static void Foo(int a, out int b, ref int c)
{
a++;
b = 20;
c++;
}
}

Page 3
DotNetTrainings – [Link] – C#

The argument “n2” is passed by reference to “b”, i.e. both “b” and “n2” reference to same memory and
hence change made to “b” is also reflected in “n2”.
Out parameter must be initialized in the method and are generally used in situations where we want to
return more than one value from the method.

Page 4

Common questions

Powered by AI

Method overloading provides flexibility by allowing same-name methods with different parameter signatures, supporting multiple use cases under one method name, useful when method intent differs with context. Optional parameters simplify calls by reducing overloads when only the number of parameters changes, ideal for scenarios needing consistent method behavior but varying argument details. Each is preferable depending on whether method purpose or argument variability is prioritized .

The 'params' keyword is beneficial when there is a need to pass a variable number of arguments to a method, allowing these arguments to be accessed as an array. This is especially useful when the number of method arguments is not known at compile time or varies between calls. Only one parameter of a method can be declared with 'params', and it must be the last in the parameter list .

Named arguments increase code clarity by allowing the caller to specify parameters by name, removing ambiguity and improving readability, especially when a method has many parameters. This also allows arguments to be supplied in a different order than the method signature. However, overusing named arguments might clutter the code and reduce readability, especially if parameters have clear logical order .

Method overloading allows the creation of multiple methods with the same name but different parameters, enhancing code organization and functionality by enabling methods to handle different types and numbers of arguments. This is resolved at compile time based on the data type and count of arguments. It allows a method to be called in different ways, depending on the contextual needs of the program .

The 'params' keyword must be used with caution because it must be the last parameter in the parameter list, and only one 'params' array is allowed per method. Improperly placing or misusing 'params' can lead to runtime errors or unintended method behavior as it can conflict with actual array arguments or be misunderstood during method invocation. Ensuring its correct usage is crucial for maintaining method integrity .

Compile-time resolution of overloaded methods optimizes performance by determining the appropriate method to call before execution, thus reducing runtime decision-making and enhancing efficiency. It helps in catching mismatched type errors early, thereby improving error handling by ensuring that the code adheres to the defined method signatures and data types, preventing type-related bugs .

Method overloading improves code maintainability by centralizing related operations under a single method name, which simplifies method management and evolution. This reduces redundancy and enhances readability, making the codebase easier to understand and modify, as developers can utilize the same logical method name for different implementations that align with various parameter sets .

Optional parameters must have default values, and once a parameter is declared as optional, all subsequent parameters must also be optional. This ensures that when calling the method, you may omit arguments from the end of the argument list. Additionally, if optional parameters are not provided, their default values are used, offering flexibility in method calls .

Passing a parameter by 'ref' means that the variable must be initialized before passing and changes made to the parameter within the method will affect the original data. In contrast, 'out' parameters do not need to be initialized before being passed, but they must be initialized within the method. Both 'ref' and 'out' allow the method to modify the passed variable, but 'out' is specifically used when the method needs to return more than one value .

Default values in optional parameters enhance program flexibility by allowing methods to be called with varying argument counts without overloading. This reduces the need for multiple method overloads with different parameter counts while maintaining default behaviors. By providing defaults, methods can offer sensible functionality without requiring the caller to specify every parameter, simplifying code maintenance and usage .

You might also like