1

I am trying to return a string using the out keyword in a method and using the returned result of both the method and the out in another method. However, even though I see it set the variable StringD in debug as soon as it goes through Method2, StringA comes in blank as Method1 begins.

I was hoping that when it set StringD to "Test" in Method2 it would then be passed back to main to be used in Method1 immediately so it could be done in two lines. Is this intended or a bug in C#? Do I have to do this with 4 lines instead?

I have listed the secondary main which just makes it into four lines which I tested and does work setting StringD to "Test"

In my main

String StringD = "";
Method1(StringD, Method2(out StringD, ""));

Secondary Main (This one works but I'd rather use the first)

String StringD = "";
Boolean BoolC = false;
BoolC = Method2(out StringD, "");
Method1(StringD, BoolC);

My methods

private void Method1(String StringA, Boolean BoolA)
{
    String StringE = "";
    Boolean BoolB = false;

    StringE = StringA;
    BoolB = BoolA;
}

private Boolean Method2(out String StringB, String StringC)
{
    StringB = "";
    if (StringC == "")
    {
        StringB = "Test";
        return true;
    }
    else
    {
       return false;
    }

 }
1
  • 1
    You should really refactor the method to return the value, rather than using an out parameter. It'll make your life much easier. Commented Jan 9, 2015 at 20:01

1 Answer 1

1

You can change parameters order in Method1

private void Method1(Boolean BoolA, String StringA)
{
    String StringE = "";
    Boolean BoolB = false;

    StringE = StringA;
    BoolB = BoolA;
}

Then call it like this:

Method1(Method2(out StringD, ""), StringD);

This way the Method2 is called before StringD is passed to the method.

Sign up to request clarification or add additional context in comments.

1 Comment

This, of course, absolutely solves your problem, but I suggest you call Method2 first, on its own line, before you call Method1. Combining it into one line is not in any way an optimization of the program, as the same variables need to be allocated and the same function calls made in the same sequence, but you've just made this chain of function calls 50x more difficult to read, understand, and debug, all to save one line of code. Case in point: the fact that this question was asked in the first place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.