0

I've been learning C# for the past few weeks now and I need to pass the return values from Method1 and Method2 into Method3 but as string parameters so that I may interpolate the values into the body of Method3. Any advice on how to do such a thing?

string Method1()
{
        //Do Stuff Here
        return result
}
string Method2()
{
        //Do Stuff Here
        return result
}
void Method3()
{
        //String Interpolation Here
}

1 Answer 1

2

I hope I understood what you're looking for Correctly. In that case this example should give you the answer you're looking for.

You can use $ infront of a string and then call method inside {}

    public static void Main()
    {
        Method3($"{Method1()} {Method2()}");
        Method4();
    }

    public static string Method1()
    {
        //Do Stuff Here
        return "Hello";
    }

    public static string Method2()
    {
        //Do Stuff Here
        return "World";
    }

    public static void Method3(string input)
    {
        // If String interpolation is done within the Method Call
        Console.WriteLine(input);
    }


    public static void Method4()
    {
        // String Interpolation, calling initial two methods from within the third method.
        Console.WriteLine($"{Method2()} {Method1()}");
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Think of $ as String.Format, if you ever need to concatenate more than two or three strings then use a StringBuilder which won't allocate new string everytime you append/concatenate.
@JeremyThompson Thanks for the additional details, should've mentioned them for clarity! The edit seems to be not what the comments show in the OPs post. I'd add it as a secondary example, not overwrite the original code.
I just added method4 which should cover both cases.

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.