- public void DoSomething(int x, string s = "test")
- {
- //Do something
- }
- //Calling methods
- DoSomething(1);
- DoSomething(2, "abc");
There are other some ways to use optional parameters.
Method overloading
- public void DoSomething(int x, string s)
- {
- //Do something
- }
- public void DoSomething(int x)
- {
- DoSomething(x, "test");
- }
params keyword
- public void DoSomething(params object[] obj)
- {
- //Do something
- }
Optional attribute
- using System.Runtime.InteropServices;
- public void DoSomething(int x, [Optional, DefaultParameterValue("test")] string s)
- {
- //Do something
- }
Nullable types
- public void DoSomething(int? x)
- {
- //Check if parameter has value
- if (x.HasValue)
- {
- //Use Value property of nullable type
- int y = x.Value;
- //Do something
- }
- else
- {
- //Do something
- }
- }
User NameValueCollection or Dictionary type parameter
- dict.Add("x",1);
- //dict.Add("s","test");
- DoSomething(dict);
- public void DoSomething(Dictionary<string, object>)
- {
- //Do something
- }