Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set a value to the element at the specified position in the one-dimensional array in C#
In C#, you can set a value to an element at a specific position in a one-dimensional array using the array indexing operator []. Array indexing in C# is zero-based, meaning the first element is at index 0, the second at index 1, and so on.
Syntax
Following is the syntax for setting a value to an array element at a specified position −
arrayName[index] = value;
Where index is the position (starting from 0) and value is the new value to be assigned.
Using Array Index Assignment
First, declare and initialize an array −
int[] arr = new int[] {55, 66, 88, 99, 111, 122, 133};
To set an element at position 2 (third element) −
arr[2] = 77;
Example
using System;
namespace Program {
public class Demo {
public static void Main(string[] args) {
int[] p = new int[] {55, 66, 88, 99, 111, 122, 133};
int j;
Console.WriteLine("Initial Array......");
for (j = 0; j < p.Length; j++) {
Console.WriteLine("arr[{0}] = {1}", j, p[j]);
}
// set new element at index 2
p[2] = 77;
Console.WriteLine("New Array......");
for (j = 0; j < p.Length; j++) {
Console.WriteLine("arr[{0}] = {1}", j, p[j]);
}
}
}
}
The output of the above code is −
Initial Array...... arr[0] = 55 arr[1] = 66 arr[2] = 88 arr[3] = 99 arr[4] = 111 arr[5] = 122 arr[6] = 133 New Array...... arr[0] = 55 arr[1] = 66 arr[2] = 77 arr[3] = 99 arr[4] = 111 arr[5] = 122 arr[6] = 133
Setting Multiple Elements
Example
using System;
class Program {
public static void Main() {
string[] fruits = {"Apple", "Banana", "Cherry", "Date"};
Console.WriteLine("Original Array:");
for (int i = 0; i < fruits.Length; i++) {
Console.WriteLine("fruits[{0}] = {1}", i, fruits[i]);
}
// Set values at different positions
fruits[1] = "Blueberry";
fruits[3] = "Dragon Fruit";
Console.WriteLine("\nModified Array:");
for (int i = 0; i < fruits.Length; i++) {
Console.WriteLine("fruits[{0}] = {1}", i, fruits[i]);
}
}
}
The output of the above code is −
Original Array: fruits[0] = Apple fruits[1] = Banana fruits[2] = Cherry fruits[3] = Date Modified Array: fruits[0] = Apple fruits[1] = Blueberry fruits[2] = Cherry fruits[3] = Dragon Fruit
Key Rules
Array indices are zero-based − the first element is at index 0.
The index must be within the valid range:
0 ≤ index < array.Length.Accessing an invalid index throws an
IndexOutOfRangeException.The assigned value must match the array's data type.
Conclusion
Setting values in C# arrays is straightforward using the indexing operator arrayName[index] = value. Remember that array indices start from 0, and always ensure the index is within the valid range to avoid runtime exceptions.
