Skip to content

C# Arrays (Console Application)

Fun with arrays!

Arrays are structures that organize related data into sets. This demo application uses the C# Array class members Length and Sort. Although this example is more fun than practical, it demonstrates how Array properties and methods can be used.

Array Overview

An array stores multiple variables. This structure is helpful with several items that are all the same data type. Numerous values referenced with one identifier is more efficient than several single variables.

In this example, we want to store several ice cream flavors. Without an array you might use:

Flavor1 = "Vanilla";
Flavor2 = "Oreo";
Flavor3 = "Mint";
//... etc

or something like:

Vanilla = "French Vanilla";
Oreo = "Oreo";
Mint = "Mint";
//... etc

However, using an array we can have all our ice cream options listed under one identifier, such as 'Flavors'.

public string[] Flavors = {"Vanilla", "Oreo", "AmeriShop Dream", "French Vanilla", "Mint", "Better Batter", "Rocky Road", "Mint Chocolate Chip", "Coffee", "Phish Food", "New York Super Fudge Chunk" };

Utility Custom Class

Custom helper functions are in a separate Utility class. The class is named Utility as these methods might be reused in other projects; searching, changing text color, and inserting spaces before content so that it appears indented. A modification of code from MSDN is also used to search through an array of values.

Class members are marked with the keyword static because the Utility class only contains helper methods. We won't make unique instances (similar to using the Console.WriteLine() method).

An abbreviated look at the Utility class:

    class Utility
    {
        static string space = "    ";
        public static void Write(string _string, bool _heading){//...}
        public static void Pause(){//...}
        public static void Title(string _title){//...}
        public static string Center(string _string){//...}
        public static string TitleCase(string _string){//...}
        public static bool Search(string[] _array, string _string){//...}
        public static void AllValues(String[] _array){//...}
    }

Length

We use the Length property when we write out how many flavors the Ice Cream shop has (how many values are in the array).

array
Using the Length property to write out the number of values in an array.

In the screenshot the value 11 is printed. The example code uses a custom function that either writes out text as a heading (with a separate color), or it operates like a tab key on a keyboard in that it inserts space between the side of the console window and the text printed. The signature for this custom method is:

public static void Write(string _string, bool _heading)

This would be better written as two separate methods (one for headings, and one for standard text), however this is a simple demo application so we'll keep it as is.

In the line of code below, first the custom method is called with Utility.Write(). Next, two arguments are passed into the method; a string to be written to the screen, and a Boolean value that indicates whether or not the text is a heading.

Array Length returns an integer (a whole number). The custom Write function is expecting a string. We pass the number into Convert.ToString() so that it will be the correct data type.

The second argument is false because this piece of content is not a heading.

Utility.Write(Convert.ToString(Flavors.Length), false);

Sort

The Array method Sort rearranges values alphabetically. The custom method AllValues writes out each value in an array.

C# Arrays: Sorting an array and printing out the values alphabetically.
Sorting an array and printing out the values alphabetically.
Array.Sort(Flavors);
Utility.AllValues(Flavors);

The AllValues method is a modification of an example at MSDN:

public static void AllValues(String[] _array)
{
    for (int i = _array.GetLowerBound(0); i <= _array.GetUpperBound(0); i++)
    {
        //space adds padding on the left side
	Console.WriteLine(space + _array[i]);
    }
    Console.WriteLine();
}       

Search, and Arrays as Arguments

The signature for the custom Search function is:

public static bool Search(string[] _array, string _string)

It is a public method that expects two arguments: an array and a search term. If the search term is found in the array, the method returns true. Otherwise it returns false.

The basic form of the method call is:

Utility.Search(ARRAY, SEARCHTERM)

The array we want to pass to Search in this case is the one that holds our flavor options (Shop.Flavors). The search term is what the player/user has typed in (input.ToLower()).

So, the method call we use is:

Utility.Search(Shop.Flavors, input.ToLower()
array
Searching an array for a term.

In the example below, the method call is part of an if/else statement to see if the search term was found.

string input = "";
Console.WriteLine("What flavor would you like?");
input = Console.ReadLine();
input = Utility.TitleCase(input);

//Passing Arrays
if (Utility.Search(Shop.Flavors, input.ToLower()))
{
        Console.WriteLine(input + " is a great choice!");
}
else
{
        Console.WriteLine("Sorry, we don't have " + input + " in stock.");
}            

The Search method used in this arrays demo application is a modification of an example at MSDN:

public static bool Search(string[] _array, string _string)
{
    bool result = false;
    int i = 0;
    foreach (string s in _array)
    {
	_array[i] = s.ToLower();
	i++;
    }

    if (Array.Find(_array, element => element == _string) == _string)
    {
	result = true;
    }
    else
    {
	result = false;
    }
    return result;
}   

C# Arrays Example Code (Ice Cream Shop)

Full code for the arrays example is below. For ease of reading, classes are listed as if there is only one file (i.e., Program.cs). Once you feel comfortable with the code, refactor and improve it!

//programmingisfun.com
using System;
using System.Globalization;

namespace ArrayAwesomeness
{
    class Program
    {
        static void Main()
        {
            Example.Run();
            Console.ReadKey();
        }
    }

    class Example
    {
        public static void Run()
        {
            IceCreamShop Shop = new IceCreamShop();
            Console.Title = Shop.Title;
            Utility.Title(Shop.Title);
            Shop.About();

            Utility.Pause();

            //Search Array
            string input = "";
            Console.WriteLine("What flavor would you like?");
            input = Console.ReadLine();
            input = Utility.TitleCase(input);

            //Passing Arrays
            if (Utility.Search(Shop.Flavors, input.ToLower()))
            {
                Console.WriteLine(input + " is a great choice!");
            }
            else
            {
                Console.WriteLine("Sorry, we don't have " + input + " in stock.");
            }
        }
    }

    class IceCreamShop
    {
        public string Title = "Ice Cream Awesomeness";
        public string[] Flavors = {"Vanilla", "Oreo", "AmeriShop Dream", "French Vanilla", "Mint", "Better Batter", "Rocky Road", "Mint Chocolate Chip", "Coffee", "Phish Food", "New York Super Fudge Chunk" };
  
        public void About()
        {
            //Length
            Utility.Write("Flavors available:", true);
            Utility.Write(Convert.ToString(Flavors.Length), false);

            //Write out all values in array
            Utility.Write("Flavors:", true);
            foreach(string s in Flavors)
            {
                Utility.Write(s, false);
            }
            Utility.Pause();

            //Sort
            Utility.Write("Flavors alphabetically:", true);
            Array.Sort(Flavors);
            Utility.AllValues(Flavors);
        }
    }

    class Utility
    {
        static string space = "    ";
        public static void Write(string _string, bool _heading)
        {
            if (_heading)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(_string);
            }
            else
            {
                Console.WriteLine(space + _string);
            }
            Console.ResetColor();
        }
        
        public static void Pause()
        {
            Console.WriteLine("Press enter to continue...");
            Console.ReadKey();
            Console.Clear();
        }

        public static void Title(string _title)
        {
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine(Center("Welcome to"));
            Console.WriteLine("\n" + Center("*´·._.·" + _title+ "·._.·`*") + "\n");
            Console.WriteLine(Center("Super Yummy!"));
            Console.ResetColor();
        }

        public static string Center(string _string)
        {
            int screenWidth = Console.WindowWidth;
            int stringWidth = _string.Length;
            int spaces = (screenWidth / 2) + (stringWidth / 2);
            return _string.PadLeft(spaces);
        }

        public static string TitleCase(string _string)
        {
            TextInfo TitleCase = new CultureInfo("en-US", false).TextInfo;
            _string = TitleCase.ToTitleCase(_string);
            return _string;
        }

        //modification of method at https://msdn.microsoft.com/en-us/library/d9hy2xwa(v=vs.110).aspx
        public static bool Search(string[] _array, string _string)
        {
            bool result = false;
            int i = 0;
            foreach (string s in _array)
            {
                _array[i] = s.ToLower();
                i++;
            }

            if (Array.Find(_array, element => element == _string) == _string)
            {
                result = true;
            }
            else
            {
                result = false;
            }
            return result;
        }

        //modification of DisplayValues method at https://msdn.microsoft.com/en-us/library/aw9s5t8f(v=vs.110).aspx
        public static void AllValues(String[] _array)
        {
            for (int i = _array.GetLowerBound(0); i <= _array.GetUpperBound(0); i++)
            {
                Console.WriteLine(space + _array[i]);
            }
            Console.WriteLine();
        }
    }

}