CinnamonBun
CinnamonBun

Reputation: 1150

Optional parameters - specify one out of several

I have a method which accepts three optional parameters.

public int DoStuff(int? count = null, bool? isValid = null, string name = "default")
{
    //Do Something
}

My question is, if I call this method and pass a single method argument:

var isValid = true;
DoStuff(isValid);

I get the the following error:

Argument 1: cannot convert from 'bool' to 'int?'

Is it possible to pass a single method argument, and specify which parameter I wish to specify?

Upvotes: 4

Views: 103

Answers (3)

Rahul
Rahul

Reputation: 77866

Currently when you call DoStuff(isValid); it's positional parameter. So it's trying to assign to count parameter which is of type int (nullable int) and throwing error.

What you are looking for is named parameter and in your case you should call it like

DoStuff(isValid:true)

So your method DoStuff parameter will have values

count = null 
isValid = true 
name = "default"

Upvotes: 1

davisoa
davisoa

Reputation: 5439

Since the first parameter is count, it is expecting an int? not a bool.

You can provide named parameters like it describes here.

DoStuff(isValid: true);

Upvotes: 12

Servy
Servy

Reputation: 203819

Yes, it is possible.

DoStuff(isValid: true);

Upvotes: 8

Related Questions