tsmt
tsmt

Reputation: 3

Automated Function Overload

I don't know if I just searched for the wrong terms, but I'd like to know if there is a possibility to automated overload functions in C# or any other programming language.

What I have:

class A
{
    public void plus(int a1, int a2, int a3, int a4 ... int an)
    {
        ...
    }
    public void plus(int a2, int a3, int a4 ... int a20)
    {
        set default value for int a1
        ...
    }
    public void plus(int a3, int a4 ... int a20)
    {
        set default value for int a1
        set default value for int a2
        ...
    }
  ... and so on
}

What I want is just one function which automatically detects how much of the parameters are given and just replace the missing with default values... without typing n functions for n parameters.

The only possibility that would come to my mind is giving null value where the default value should be used, like:

class A
{
    public void plus(int a1, int a2, int a3, int a4 ... int an)
    {
        if(a1 == null)
            a1 = 1;
        if(a2 == null)
            a2 = 2;
         ...
    }
}

But that wouldn't support my requirement that i can use these function terms:

plus(1,2,3);
plus(1,2,3,4);
plus(1,2);
plus(1,2,3,4,5,6);

PS: In my actual problem (which I'm not sure about if I'm allowed to post), it's a lot more than just a plus operation. It builds a parameter for starting a tool:

public string buildParameters(int a, int b, string c, double d (heheheh), Class C, Object D, etc...) {...} 

No I had another Idea to solve this:

class Builder
{
    public string buildParameters(int p1, int p2, string p3, double p4, char p5)
    {
        // Build String
        // build build
        // End
        return "blabla";
    }
    public string buildParameters(int p1, int p2, string p3, double p4)
    {
        return buildParameters(p1, p2, p3, p4, 'c');
    }
    public string buildParameters(int p1, int p2, string p3)
    {
        return buildParameters(p1, p2, p3, 0.00, 'c');
    }
    public string buildParameters(int p1, string p3)
    {
        return buildParameters(p1, 2, p3, 0.00, 'c');
    }
}

depending on which parameters are given or not... That's not as much to write as in my first try, but still a lot of text -.-

Upvotes: 0

Views: 111

Answers (2)

Pontus Gagge
Pontus Gagge

Reputation: 17258

If you have homogenuous parameters, use params instead. Some languages have similar constructs, e.g. C++11.

However, with many different parameter types, you could use named arguments and defaults.

Upvotes: 2

Simon Whitehead
Simon Whitehead

Reputation: 65049

C# (as of C# 4) supports default values.. however they must be the last arguments in the argument list.

As below:

public void plus(int a1, int a2, int a3 = 1, int a4 = 2, int a5 = 3)

etc.

Upvotes: 1

Related Questions