Tuesday 22 September 2015

Optional and Named Parameters in C# 3.0

Hi,
 
Recently in one of our project we got a requirement to change a method which should be one more parameter. The method is used in multiple places, changing in all places is not the correct approach. Then, we thought of writing over loaded method. Then I just did quick search and came to know about Optional and Named Parameters.
 
Named and optional parameters are really two distinct features, and allow us to either omit parameters which have a defined default value, and/or to pass parameters by name rather than position
 
Optional Parameters - allow us to omit arguments to members without having to define a specific overload matching.
 
Named Parameters - are passed by name instead of relying on its position in the parameter list.
 
Here is the one simple example.

static void Main()
{
      // General Method Calling.
      CheckOptionalAndNamedParameters(6, "Gopinath");
      // with out optional parameters.
      CheckOptionalAndNamedParameters();
      // with out second optional parameter.
      CheckOptionalAndNamedParameters(6);
      // We cannot call the method by skipping the first parameter and passing the second.
      // CheckOptionalAndNamedParameters("Dot");
      // Specify one named parameter.
      CheckOptionalAndNamedParameters(strValue: "Gopinath");
      // Specify both named parameters.
      CheckOptionalAndNamedParameters(intValue: 6, strValue: "Gopinath");
      Console.Read();
}

static void CheckOptionalAndNamedParameters(int intValue = 1, string strValue = "Test")
{
      Console.WriteLine("Integer Value = {0}, String Value = {1}", intValue, strValue);
}

Hope this helps.
 
--
Happy Coding
Gopinath

No comments:

Post a Comment