Geeks With Blogs
Code.Blog Code Talk for the Game Developer

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:
Posted on Friday, August 29, 2008 11:14 AM Tutorials | Back to top


Comments on this post: Code a la Carte: Displaying Arrays (C#)

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Matthew Christian | Powered by: GeeksWithBlogs.net