1

I have a method that takes one dynamically typed (probably not relevant) parameter and multiple optional parameters of more than one type. Is there any way to specify which parameters you are passing?

With this code I am getting compiler errors (below), and I wold like not to have to write overloads or rewrite the function with multiple orders for the optional parameters.

  • Error 2 Argument 3: cannot convert from 'string' to 'bool'
  • Error 1 The best overloaded method match for Index(int, bool, bool, string)' has some invalid arguments

Code:

public void DoSomeWork()
{
    Index<int>(Id, false,"test"); //compiler error 
}

private void Index<T>(T o, bool flush = false, bool userDispose = true, string starter = "stop")
{

}
0

2 Answers 2

6

You can mark optional parameters with the name followed by a double point. In your example:

public void DoSomeWork()
{
    Index<int>(Id, false, starter: "test");
}

This means that Id and false names the first two parameters o and flush, the third parameter userDispose is not set and the parameter starter is set with test.

For more informations about named and optional parameters, have a look at the MSDN.

Sign up to request clarification or add additional context in comments.

2 Comments

Interresting, I didn't know that !
Thanks, exactly what I was looking for (will mark as answer as soon as it lets me).
3

Use named arguments, which is one of the great features of C#.

 Index<int>(Id, flush: false, starter: "test"); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.