FreeJobAlert.Com

Government Jobs | Results | Admit Cards

Csharp 4.0 feature – Named and optional arguments

Optional arguments allow you to omit arguments when calling methods. This is done by defining a method with assigning default values to parameters.

See the below code snippet to better understand
Declaration of method

public void testMethod(int a, int b = 50, int c = 100);

Now this method can be called as below ways.


testMethod(10, 30, 50);
// This is a normal call as 3 arguments were passed

testMethod(10, 30);
// This call is omitting parameter "c". This call is equalant to SomeMethod(10, 30, 100)

testMethod(10);
// This call is omitting both "b" and "c". This call is equalant to SomeMethod(10, 50, 100)

Named Arguments allows you to pass the arguments by the corresponding parameter names.

The above testMethod can be called


testMethod(a:10, b:30, c:50);

By this feature, we don’t need to pass the arguments in the order of parameters defined in the method. We can rewrite the above method call as shown below.

testMethod(c:50, b:30, a:10);

And you can solve the above discussed problem (omitting the middle parameter “b”) as shown below.


testMethod(a:10, c:50);
// This call Omits the parameter "b".

Tags: .Net Framework, .net interview questions and answers, c sharp features, c sharp interview questions, csharp 4.0, csharp 4.0 new features, named parameters .net, named parameters csharp, optional parameter in c sharp

Leave a Comment