Optional parameters - specify one of several

I have a method that takes 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 one argument to the method:

var isValid = true;
DoStuff(isValid);

I get the following error:

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

Is it possible to pass one argument to a method and indicate which parameter I want to specify?

+4
source share
3 answers

Since the first parameter count, it expects int?not a bool.

You can specify named parameters, such as here .

DoStuff(isValid: true);
+12
source

Yes it is possible.

DoStuff(isValid: true);
+8
source

Currently, when you call DoStuff(isValid);its positional parameter. Therefore, it tries to assign a parameter countthat is of type int (nullable int) and a throwing error.

What you are looking for is named parameterand in your case you should call it as

DoStuff(isValid:true)

So your method DoStuffwill make a difference

count = null 
isValid = true 
name = "default"
+1
source

Source: https://habr.com/ru/post/1536491/


All Articles