c-sharp
  1. c-sharp-arrays

C# Arrays

In C#, arrays are used to store a collection of elements of the same data type. They provide a convenient way to work with a set of values under a single variable name. This guide covers the basics of working with arrays in C#.

Syntax

// Declare an array
dataType[] arrayName;

// Initialize an array
dataType[] arrayName = new dataType[size];

// Example: Integer array
int[] numbers = new int[5];


## Example

```csharp
// Declare and initialize an array of strings
string[] fruits = new string[] { "Apple", "Banana", "Orange", "Mango", "Grapes" };

Output

The output is the array fruits containing the specified strings.

Explanation

  • The dataType represents the type of elements the array will store (e.g., int, string).
  • arrayName is the name given to the array variable.
  • The new dataType[size] syntax allocates memory for an array of a specific size.

Use

Arrays in C# are used when:

  • You need to store and manage a collection of elements of the same type.
  • Random access to elements is required based on their index.
  • Iterating through a set of values is necessary.

Important Points

  • Arrays are zero-indexed, meaning the first element has an index of 0.
  • Use the Length property to get the number of elements in the array.
  • Arrays can be of primitive types, custom types, or even reference types.

Summary

C# arrays provide an efficient way to work with collections of elements. They are versatile and widely used in various programming scenarios. Understanding array syntax, initialization, and common operations will empower you to effectively use arrays in your C# applications. Whether dealing with simple data types or custom objects, arrays are a fundamental construct in C# programming.

Published on: