C# Optional Parameters

Optional parameters were introduced with .NET 4.0. You just only give default value these parameters.

  1. public void DoSomething(int x, string s = "test")
  2. {
  3.    //Do something
  4. }

  1. //Calling methods
  2. DoSomething(1);
  3. DoSomething(2, "abc");


There are other some ways to use optional parameters.
Method overloading

  1. public void DoSomething(int x, string s)
  2. {
  3.    //Do something
  4. }
  5.                
  6. public void DoSomething(int x)
  7. {
  8.    DoSomething(x, "test");
  9. }


params keyword

  1. public void DoSomething(params object[] obj)
  2. {
  3.    //Do something
  4. }


Optional attribute

  1. using System.Runtime.InteropServices;
  2.  
  3. public void DoSomething(int x, [Optional, DefaultParameterValue("test")] string s)
  4. {
  5.    //Do something
  6. }


Nullable types

  1. public void DoSomething(int? x)
  2. {
  3.    //Check if parameter has value
  4.    if (x.HasValue)
  5.    {
  6.        //Use Value property of nullable type
  7.        int y = x.Value;
  8.  
  9.        //Do something
  10.    }
  11.    else
  12.    {
  13.        //Do something
  14.    }
  15. }


User NameValueCollection or Dictionary type parameter

  1. Dictionary<string, object> dict = new Dictionary<string, object>();
  2. dict.Add("x",1);
  3. //dict.Add("s","test");
  4. DoSomething(dict);

  1. public void DoSomething(Dictionary<string, object>)
  2. {
  3.    //Do something
  4. }

m ant / Mechanical Ant