3Pi
3Pi

Reputation: 1914

Not giving an 'out' argument

It is possible to assign default values to normal arguments to a function, such that

bool SomeFunction(int arg1 = 3, int arg2 = 4)

can be called in any of the following ways.

bool val = SomeFunction();
bool val = SomeFunction(6);
bool val = SomeFunction(6,8);

Is there a way of doing something similar (other than just creating an unused variable) such that

bool SomeOtherFunction(int arg1, out int argOut)

can be called in either of the following ways?

int outarg;
bool val = SomeOtherFunction(4,outarg);
bool val = SomeOtherFunction(4);

Is this at all possible, or if not, what are good workarounds? Thanks.

Upvotes: 3

Views: 83

Answers (4)

Tu Tran
Tu Tran

Reputation: 1977

There is no default argument in C#, to do the similar thing, you should implement overload method. Or you can use this, which you must handle the arguments by yourself

Upvotes: -1

yamen
yamen

Reputation: 15618

Yes, use an overloaded version of the same method that doesn't take a second argument:

public bool SomeOtherFunction(int arg1)
{
    int ignore;
    return SomeOtherFunction(arg1, out ignore);
}

Upvotes: 1

manojlds
manojlds

Reputation: 301147

No, ref and out parameters cannot have default values. Workarounds will depend on what exactly you want to achieve. One way is to wrap it into another method (or overload ) and pass the out variable from that method.

Upvotes: 0

K-ballo
K-ballo

Reputation: 81349

A good workaround is:

bool SomeOtherFunction(int arg1, out int argOut){ ... }

bool SomeOtherFunction(int arg1)
{
    int dummyArgOut;
    return SomeOtherFunction(arg1, dummyArgOut);
}

I'd even say its the best workaround.

Upvotes: 6

Related Questions