Monday, June 13, 2011

Named and Optional Arguments – What’s new in C# 4.0

Microsoft introduced new feature called Named and optional arguments in C# 4.0. This feature is already available in Visual Basic. This feature allows user to enter optional and named arguments with method parameters. These are two different features but mostly used together.

Optional parameter is declared by simply declaring default value for it. In below example parameter “s” and “b” are optional parameters. If you don’t specify any arguments for optional parameters it will use default values. You can specify optional parameters for Method, Constructor and indexer.  

private void Test(int a, string s= "Test", bool b= false)

Test(45, "Mitesh", true); // Valid
Test(33); // Valid
Test(44, false); // Invalid

C# doesn’t allow you to omit arguments between commas instead you can specify name with argument. You don’t need to remember order of parameters you simply specify argument with name of parameter.  

Test(44 ,, false); // Invalid, Comma separated gapes are not allowed


Test(44 ,b:false); // Valid
Test(36, b:true, s:"MyName"); // Valid
Test(b:true, 56); // Invalid, Named arguments must be specified after all fixed arguments

  • Optional parameters must be added only after all required parameters.
  • Named arguments must be specified after all fixed arguments.

    Note: Ref keyword is also optional when you using COM and passing object as reference.

    No comments:

    Post a Comment