Henley Wing Chiu
Henley Wing Chiu

Reputation: 22515

C#: How to pass parameter key/values to a function?

I have a function that takes in a bool, shown below:

public void LoadEndPoints(bool mock)
{

}

I can call this via LoadEndpoints(true) or LoadEndpoints(false), but this can be a bit hard to understand, as you need to know what true/false represents. Is there a way to pass the parameter name and value to a function such as LoadEndPoints(mock = true)?

Upvotes: 1

Views: 776

Answers (5)

p.s.w.g
p.s.w.g

Reputation: 149020

Yes!

You can specify the parameter names like this:

myObject.LoadEndPoints(mock: true);

Further Reading

Another way to improve readability of your code would be to use an enum, like this:

public enum LoadOption
{
    Normal,
    Mock
}

public void LoadEndPoints(LoadOption option)
{
    ...
}

Then the call would look a bit like this:

myObject.LoadEndPoints(LoadOption.Mock);

Upvotes: 3

aquaraga
aquaraga

Reputation: 4168

You could use 'Named arguments', a C# 4.0 feature; and thus call: myObject.LoadEndPoints(mock : true);

If readability is indeed your prime concern, you could even expose two explicit methods, and internally reuse the logic - something similar to:

    public void LoadEndPointsWithoutMock()
    {
        LoadEndPoints(false);
    }
    public void LoadEndPointsByMocking()
    {
        LoadEndPoints(true);
    }
    private void LoadEndPoints(bool mock)
    {

    }

Also, I wouldn't say that LoadEndPointsWithoutMock, etc. are great method names. Ideally, the names should have something to do with the domain.

Upvotes: 2

Alex
Alex

Reputation: 19

Use named parameters. Have a look at this Named and Optional Arguments

Upvotes: 0

Kenneth
Kenneth

Reputation: 28737

Yes, you can do it with the following syntax in c#:

myObject.LoadEndPoints(mock : true);

And in VB:

myObject.LoadEndPoints(mock := true)

Upvotes: 0

Jonesopolis
Jonesopolis

Reputation: 25370

You can use a KeyValuePair:

   KeyValuePair kvp = new KeyValuePair(BoolType, BoolValue)

Upvotes: 1

Related Questions