Method parameter is one of the integral part of programming and it also applies with C# programming Language.
We can categorize method parameters in various parts. Some of them are:
- Named Parameters (C# 4.0 and above)
- Ref Parameter (Passing Value Types by Reference)
- Out Parameters
- Default Parameters or Optional Arguments (C# 4.0 and above)
- Dynamic parameter (dynamic keyword).
- Value parameter or Passing Value Types by Value (normal C# method param are value parameter)
- Params (params)
Named Parameters
In C# 4.0 a new type of argument iis introduced known as named parameter. Using this feature we can specify the value of a parameter by parameter name regardless of its ordering in method. I am using a simple method to explain it. Have a look at the following screenshot.
It provides an ease for user because sometimes we may have 10-20 parameters in a method. In that case we need to remember ordering of all those parameters. But if we use the default parameter feature of C# then we do not need to remember any ordering. This feature is available in C# 4.0 and above versions (C#, C# 6).
Suppose we have a method like the following code snippet,
- SomeObject(double width, double height, double length, double weight, double volume, double density, bool isMetal, bool isConductor)
Then we need to remember all the parameter and its ordering but Named parameter makes it easy.
The code snippet will be something like the following:
- private void SomeObject(double width, double height, double length, double weight, double volume, double density, bool isMetal, bool isConductor)
- {
-
- }
- static void Main(string[] args)
- {
- Program p = new Program();
- p.SomeObject(10.0, 20.0, isConductor: true, isMetal: true, length: 50.0, weight: 100.0, density: 50.0, volume: 200.0);
- }
- private void SomeObject(double width, double height, double length, double weight, double volume, double density, bool isMetal, bool isConductor)
- {
-
- }
But all the named parameters must appear after fixed arguments. If we provide any fixed argument after named argument then it will give the following compile time error “
Named argument specifications must appear after all fixed arguments have been specified”.
Advantages of Named Parameter- Named parameter provide us the facility to do not remember the parameter ordering.
- Improves the readability of code.
- Easy to understand.
- Due to readability it also reduces the chances of bug in application.
Disadvantages of Named Parameter
- Its performance is slower as compared to fixed argument. It should be avoided if it does not change the readability and understanding of code to a great extent.
- Due to slower performance we can also say that it is syntactic sugar over fixed parameter calls.
Default Parameters or Optional Arguments (C# 4.0 and above)
In C# 4.0 along with named parameter another method parameter feature introduced known as Default Parameters or Optional Arguments. Default parameter can be used with method, constructor, delegates and indexer. For method, constructor, delegates and indexer we can specify which parameter is required (fixed) and which is optional. Any call can omit arguments for optional parameter but it must specify the value for required (fixed) parameter.
Optional parameter must be defined after any required parameter.
While calling the method having optional parameter if we provide value for an optional parameter then we must provide value for all preceding optional parameters.
E.g.
- private void Add(int w, int x = 10, int y = 0, int z = 5)
- {
-
- }
- Program p = new Program();
- p.Add(15);
-
- p.Add(15, 10);
If you want to pass value for y, then you must specify value for x also. e.g.
But this can be done using named parameter,
As you can see in above screenshot IntelliSense uses brackets to indicate optional parameters.
Optional parameter in Constructor
In the same way we can use it with indexer and delegate.
Named and optional arguments also support dynamic objects and greatly improve interoperability with COM APIs.
Ref Parameter (Passing Value Types by Reference)
In C# by default we pass the parameter by value also known as value parameter. But a parameter also can be passed by reference. To pass an argument with reference we need to use "ref" keyword. If any argument passed as reference then any change to the parameter in the called method is reflected in the calling method.
I want to clarify that the concept of reference type and passing arguments by reference type is entirely different concept.
Any argument being passed by reference must be assigned before passing it to the method. If it is not assigned then it will give compile time error.
E.g:- private void Add(ref int w, ref int x)
- {
-
- }
- Program p = new Program();
- int firstParam;
- int secondParam;
- p.Add(ref firstParam, ref secondParam);
Will throw the following error “
Use of unassigned local variable 'firstParam'”,
Now assign value for those parameters and error will gone.
- int firstParam = 0;
- int secondParam = 0;
Out Parameters
An out param is similar to ref param. But any argument passed as out parameter need not to be initialized whereas in case of ref it must be initialized. Another difference is that ref parameter may be assigned inside the method in which it is called (not necessary), but in case of “out” it must be assigned in the calling method before any exit.
Dynamic parameter (dynamic keyword):
A parameter can also be passed dynamically like the following code snippet.
- namespace DynamicParams
- {
- class Program
- {
- static void MyDynamicMethod(dynamic dynamicparam)
- {
- dynamicparam.DoSomethingDynamic();
- }
- static void Main(string[] args)
- {
- MyDynamicMethod("dynamicValue");
- }
- }
- }
Value parameter or Passing Value Types by Value (normal C# method param are value parameter):Normal C# method param are value parameter. It is also known as “
passing value types by value” or we can say that when a variable is passed as value type then it contains its data directly not the reference. If any changes made in the value type parameter it will not reflect the original data stored as argument. If we need to modify original data we can pass it using 'ref' or 'out' keyword. e.g.
- static void Main(string[] args)
- {
- int a = 10;
- int b = 25;
- int res = Add(a, b);
- }
- public static int Add(int x, int y)
- {
- return x = y;
- }
Ordering of parameters in Method:
Ordering matters in most of the cases. Some of them are:
- Default parameter
- Method overloading
- Method overriding
- Value parameter
It does not matter for Named Parameters.
Params (params)
The ‘param’ keyword can be used to specify a method parameter that takes a variable number of arguments. When we use ‘param’ keyword to pass variable number of arguments we can send any number of arguments or no arguments. But all the arguments passed should be of same type.
If a method is using param keyword it cannot have any other parameter i.e. no additional parameter allowed.
- using static System.Console;
- namespace paramsTypeParameter
- {
- class Program
- {
- static void Main(string[] args)
- {
- string my1stLine = "This is my first Line";
- string my2ndLine = "This is my second Line";
- string my3rdline = "This is my Third Line";
- string my4thline = "This is my fourth Line";
- PrintPassedList(my1stLine, my2ndLine, my3rdline, my4thline);
- }
- public static void PrintPassedList(params string[] listtoPrint)
- {
- foreach(var item in listtoPrint)
- {
- WriteLine(item);
- }
- }
- }
- }
Output