Search code examples
c#methodsout

out keyword not working with method in method in C#


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;
    }

 }

Solution

  • 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.