Code a la Carte: Displaying Arrays (C#)

Today's Code a la Carte is quite simple but is often a mistake with many new programmers.  First, let's look at an example and the resulting output.

Example Code:

using System;
 
namespace ArrayDisplayExample
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] saNames = new string[3];
            saNames[0] = "Matt";
            saNames[1] = "Steven";
            saNames[2] = "Anna";
 
            Console.WriteLine(saNames);
            Console.Read();
        }
    }
}
 

Output:

 

Reason:

 

The reason this is displayed, is because you can't pass an array the same as a String variable.  Passing an array will display the type of array because you are passing an array and saying 'Print out what this is' instead of 'Print out what is contained in here'.  The solution, is to loop through the array and print each item as follows:

 

using System;
 
namespace ArrayDisplayExample
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] saNames = new string[3];
            saNames[0] = "Matt";
            saNames[1] = "Steven";
            saNames[2] = "Anna";
 
            for (int i = 0; i < saNames.Length; i++)
            {
                Console.WriteLine(saNames[i].ToString());
            }
 
            Console.Read();
        }
    }
}
 
Output:
Print | posted on Friday, August 29, 2008 11:14 AM

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: