C# default parameter by name is this possible?

May be this is a stupid question but: I wonder if there is something like default parameter but not by value - but by name.


I must use a parameter "IWebDriver driver" in a lot of my methods. And I know that always when I use it I will use the name "driver" - the "object" behind the name can be different(IE, FF, Chrome..) but the name will always be the same.

So is this possible to have a function

public void CheckName(string nameToCheck, string expectedValue, IWebDriver driver = driver with name "driver")  
   some code....

And when I use it NOT to do:

CheckName("MyName", "MyName", driver)  

but to do:

CheckName("MyName", "MyName")

... and the method knows that must get the object with name(string) "driver".

If I want to use other name than default just to specify it:

CheckName("MyName", "MyName", driverOtherName)
Jon Skeet

No, there's no way of doing that. Default parameters have to have constant values - they can't depend on a value taken from a local variable.

It sounds like you should probably construct an instance which stores a driver reference in a field, then you can just call the methods on that instance and it can use the value from the field:

public class FooChecker
    private readonly IWebDriver driver;

    public FooChecker(IWebDriver driver)
        this.driver = driver;

    public void CheckName(string nameToCheck, string expectedValue)
        // Use driver here

Then you can use:

var checker = new FooChecker(driver);
checker.CheckName("MyName", "MyName");
checker.CheckName("MyName2", "MyName2");


See more on this question at Stackoverflow