Reputation: 1955
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.
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")
{
}
Upvotes: 1
Views: 222
Reputation: 101681
Use named arguments, which is one of the great features of C#.
Index<int>(Id, flush: false, starter: "test");
Upvotes: 3
Reputation: 4727
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.
Upvotes: 6