Techaray

Shailendra Saxena's Technical Blog

Optional Parameters in C#

clock February 3, 2013 06:24 by author ShailendraSaxena

 

You specify that a parameter is optional when you define a method by providing a default

value for the parameter. You indicate a default value by using the assignment operator. In the

optMethod method shown next, the first parameter is mandatory because it does not specify

a default value, but the second and third parameters are optional:

 

void optMethod(int first, double second = 0.0, string third = "Hello")

{

...

}

 

You must specify all mandatory parameters before any optional parameters.

 

You can call a method that takes optional parameters in the same way that you call any other

method; you specify the method name and provide any necessary arguments.

 

The difference with methods that take optional parameters is that you can omit the corresponding

arguments, and the method will use the default value when the method runs.

In the following example code, the first call to the optMethod method provides values for all three parameters. The second call specifies only two arguments, and these values are applied to the first and second parameters. The third parameter receives the default value of “Hello” when

the method runs.

 

optMethod(99, 123.45, "World"); // Arguments provided for all three parameters

 

optMethod(100, 54.321); // Arguments provided for 1st two parameters only



Access Modifiers in C#

clock January 6, 2013 23:25 by author ShailendraSaxena

 

Declared accessibility

Meaning

public

Access is not restricted.

protected

Access is limited to the containing class or types derived from the containing class.

internal

Access is limited to the current assembly.

protected internal

Access is limited to the current assembly or types derived from the containing class.

private

Access is limited to the containing type.



Search

Calendar

<<  August 2017  >>
SuMoTuWeThFrSa
303112345
6789101112
13141516171819
20212223242526
272829303112
3456789

Archive

Tags

Categories


Visitors

FlagCounter

Flag Counter

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2017

Sign In