LukAss741
LukAss741

Reputation: 831

variable order of parameters in function

I have a function:

public static bool Substr(string source, out string output, string begining, int length = -1, string end = null)
{
    output = "";
    int start_;
    if ((start_ = source.IndexOf(begining, StringComparison.Ordinal)) != -1)
    {
        start_ += begining.Length;
        if (length != -1)
        {
            if (start_ +length <= source.Length)
            {
                output = source.Substring(start_, length);
                return true;
            }
        }else{
            int end_;
            if ((end_ = source.IndexOf(end, start_, StringComparison.Ordinal)) != -1)
            {
                output = source.Substring(start_, end_ -start_);
                return true;
            }
        }
    }
    return false;
}

which I currently use as:

string in = "aaaaaaa(bbbbbb)";
string result = Substr(in, out result, "(", -1, ")");

where end of substring is ")" but I have to write -1 which I don't use because 4th parameter is expected to be int

or like this:

string in = "aaaaaaa(bbbbbb)";
string result = Substr(in, out result, "(", 6);

where end of substring is 6th char after "("

How can I make 4th parameter either int or string so I can use it as:

string result = Substr(in, out result, "(", ")");

My inspiration are c# native functions such as infexOf:

string i = "aaaaa(bbbb)";
int x = i.IndexOf("(", 3, StringComparison.Ordinal);
int y = i.IndexOf("(", StringComparison.Ordinal);

where in this case second parameter is either int or StringComparison.

How do I make compiler decide by parameter data type instead of expecting exact order of parameters? Note that I am not looking for "Named and Optional Arguments" https://msdn.microsoft.com/en-us/library/dd264739(v=vs.100).aspx

Upvotes: 2

Views: 486

Answers (1)

Ondrej Tucny
Ondrej Tucny

Reputation: 27974

How do I make compiler decide by parameter data type instead of expecting exact order of parameters?

You don't. This is just not possible and wouldn't even work in many cases.

Note that I am not looking for "Named and Optional Arguments"

If you must, for whatever reason, avoid named arguments (note that you are already using optional arguments anyway), go ahead with multiple overloads:

public static bool Substr(string source, out string output, string begining, int length, string end)
public static bool Substr(string source, out string output, string begining, string end)
public static bool Substr(string source, out string output, string begining, int length)
public static bool Substr(string source, out string output, string begining)

Each of the overloads with less parameters just calling the one implementation with most parameters.

Upvotes: 2

Related Questions