Optional and Named Parameters in C# 3.0

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.
      // with out second optional parameter.
      // 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”);

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

Hope this helps.

Happy Coding

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s