0
0
C Sharp (C#)programming~5 mins

Why arrays are needed in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Arrays help us store many items together in one place. This makes it easy to keep and use a list of things like numbers or names.

When you want to keep a list of student scores in a test.
When you need to store daily temperatures for a week.
When you want to save multiple names of friends in one variable.
When you want to process a collection of items one by one.
When you want to pass many values to a method at once.
Syntax
C Sharp (C#)
class Program
{
    static void Main()
    {
        // Declare an array of integers
        int[] numbers = new int[5];

        // Declare and initialize an array
        string[] names = { "Alice", "Bob", "Charlie" };
    }
}

An array holds items of the same type together.

You must specify the type and size when creating an array.

Examples
This creates an empty array with zero length.
C Sharp (C#)
int[] emptyArray = new int[0];
// An array with no elements
This array holds just one number.
C Sharp (C#)
int[] singleElementArray = { 42 };
// An array with one element
This array holds three fruit names.
C Sharp (C#)
string[] fruits = { "Apple", "Banana", "Cherry" };
// An array with multiple elements
Sample Program

This program shows how to create an array, print its items, change one item, and print again.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        // Create an array to hold 3 colors
        string[] colors = { "Red", "Green", "Blue" };

        Console.WriteLine("Colors before change:");
        foreach (string color in colors)
        {
            Console.WriteLine(color);
        }

        // Change the second color
        colors[1] = "Yellow";

        Console.WriteLine("\nColors after change:");
        foreach (string color in colors)
        {
            Console.WriteLine(color);
        }
    }
}
OutputSuccess
Important Notes

Accessing an array element by index is very fast (constant time).

Arrays use a fixed amount of memory based on their size.

Common mistake: Trying to access an index outside the array size causes an error.

Use arrays when you know the number of items in advance and want fast access.

Summary

Arrays store many items of the same type together.

They make it easy to keep and use lists of data.

Arrays have a fixed size and fast access by position.