Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we declare Optional Parameters in C#.net? [duplicate]

Tags:

c#

optional

I am using a method for doing some action, i want the method to be written only once by using Optional Parameters in C#, other than Method Overloading is there any?

like image 789
Sai Kalyan Kumar Akshinthala Avatar asked Feb 25 '11 11:02

Sai Kalyan Kumar Akshinthala


People also ask

What is optional in C function declaration?

The optional declaration-specifiers and mandatory declarator together specify the function's return type and name. The declarator is a combination of the identifier that names the function and the parentheses following the function name.

How do you make a function parameter optional?

Using the Logical OR operator ('||') In this method, the optional parameter is "Logically ORed" with the default value within the body of the function. In the example below, if the value of b is undefined, 2 is passed instead.

Which function declares an optional parameter?

To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.


2 Answers

New to visual studio 2010

named and optional arguments

for example

public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
{
}
like image 166
Richard Friend Avatar answered Oct 05 '22 11:10

Richard Friend


Have a look at following code

Library to use

using System.Runtime.InteropServices;

Function declaration

private void SampleFunction([Optional]string optionalVar, string strVar)
{
}

And while giving call to function you can do like this

SampleFunction(optionalVar: "someValue","otherValue");

OR

SampleFunction("otherValue");

Reply if it helps.!:)

like image 43
Akshay Avatar answered Oct 05 '22 12:10

Akshay