Search code examples
c#arraysforeachmessagebox

C# Array Contents not showing, but type is


public partial class Form1 : Form
{
    private string[] myArray = { "Eddie", "Amber", "Kelly" };

    public void showMe()
    {
        foreach (string i in myArray) 
            MessageBox.Show(myArray.ToString()); 

    }

    private void button1_Click(object sender, EventArgs e) => showMe();
}

Hi everybody,

I'm trying to get the names from myArray to be shown in the MessageBox, but all I'm getting is a MessageBox with System.String[] and I'm not sure why? Can someone please tell me what I'm doing wrong?

Thanks

Eddie


Solution

  • That's the default behaviour of ToString(). It just prints the type name of the object, unless defined otherwise for a specific type.

    You want to use

    foreach (string i in myArray)
        MessageBox.Show(i);
    

    to display a separate messagebox for each element in the array or

    MessageBox.Show(string.Join(",", myArray));
    

    to display a single messagebox with all elements of the array.