xxxxxxxxxx
public void SomeMethod(int a, int b = 0){/*some code*/}
xxxxxxxxxx
// Using Attribute
private void SomeMethod([Optional] string param)
{
}
// Using Default Values
private void SomeMethod(string param = null)
{
}
xxxxxxxxxx
// Using Optional Attribute
private void SomeMethod([Optional] string param)
{
}
// Using Default Values
private void SomeMethod(string param = null)
{
}
xxxxxxxxxx
public void ExampleMethod(int required,
string optionalstr = "default string",
int optionalint = 10)
C#, you can make a parameter optional by specifying a default value for that parameter in the method signature.
xxxxxxxxxx
public void MyMethod(string requiredParam, int optionalParam = 0)
{
// method body
}
the optionalParam parameter has a default value of 0, so it's optional. If you call MyMethod without providing a value for optionalParam, it will default to 0. If you provide a value for optionalParam, it will use the provided value instead of the default value. The requiredParam parameter does not have a default value, so it must always be provided when calling MyMethod.
xxxxxxxxxx
Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list aren't supported. For example, in the following code, instance method ExampleMethod is defined with one required and two optional parameters.
C#
Copy
public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
The following call to ExampleMethod causes a compiler error, because an argument is provided for the third parameter but not for the second.
C#
Copy
//anExample.ExampleMethod(3, ,4);
However, if you know the name of the third parameter, you can use a named argument to accomplish the task.
C#
Copy
anExample.ExampleMethod(3, optionalint: 4);
c# optional parameters
xxxxxxxxxx
public int ExampleMethod (int optional = 5)
{
Console.WriteLine(optinonal);
}
ExampleMethod(); // output: 5
ExampleMethod(8); // output: 8
xxxxxxxxxx
// Example of using optional parameters in C#
class MyClass
{
public void MyMethod(int x, int y = 10)
{
int result = x + y;
Console.WriteLine("Result: " + result);
}
}
// Usage
MyClass myObject = new MyClass();
myObject.MyMethod(5); // Output: Result: 15 (y has the default value of 10)
myObject.MyMethod(5, 7); // Output: Result: 12 (y is assigned the value of 7)