SaurabhCooks SaurabhCooks - 25 days ago 7
C# Question

Passing an array to the method.

I have written a simple code and have passed an array to the method and have returned the value and trying to get it printed. Somehow, I am not getting the required output. Please point out where I got wrong. Also tips to make the code concise are most welcome.

static void Main(string[] args)
{
string[] ar = new string[] { "hello", "world", "people" };

writeString(ar);
Console.WriteLine(ar);

Console.ReadLine();

}

static string writeString(string[] ar)
{
string a1 = " ";
foreach (string a in ar)
{
a1 = a1 + a;
}
return a1;
}

Answer

I hope the code sample makes it clear. You have to capture the return value from the writeString function and output that.

static void Main(string[] args)
{
    string[] ar = new string[] { "hello", "world", "people" };

    string output = writeString(ar);
    Console.WriteLine(output);

    Console.ReadLine();

}

static string writeString(string[] ar)
{
    string a1 = " ";
    foreach (string a in ar)
    {
        a1 = a1 + a;
    }
    return a1;
}