In C#, SetValue writes an element into an array at the index (or indexes) you provide. The value is passed as object and must be compatible with the array’s element type.
Prefer arr[i] = value for typed arrays. Use SetValue when working with Array or multi-dimensional indexes in a generic helper.
This is an instance member of System.Array. You call it on an array variable with a dot, such as arr.SetValue(...). Arrays in C# have a fixed length after creation; use List<T> when the count must grow.
Syntax
Call SetValue with the value first, then the index or indexes.
C#
nums.SetValue(99, 1);
grid.SetValue("Z", 1, 2);
Call
What it does
nums.SetValue(99, 1)
Writes 99 at index 1.
grid.SetValue("Z", 0, 1)
Writes Z at [0,1].
A wrong runtime type throws. Match the array’s element type.
Library declarations
C#
public void SetValue(object value, int index);
public void SetValue(object value, int index1, int index2);
public void SetValue(object value, params int[] indices);
Parameters
Parameter
Description
value
Required. New element value (compatible type).
index / indices
Required. One index per dimension.
Return Value
Return Value
Description
void
The element is updated in place.
C# Examples
Example 1 — Write Into a 1D Array
Replace one int and print the array.
C#
using System;
class Program {
static void Main() {
int[] nums = { 1, 2, 3 };
nums.SetValue(99, 1);
Console.WriteLine(string.Join(", ", nums));
}
}
Output
1, 99, 3
How It Works
Value first. SetValue takes the new value, then the index.
Index 1. Middle slot becomes 99.
Others unchanged. 1 and 3 stay.
Same as nums[1]=99. Indexer is fine for typed arrays.
using System;
class Program {
static void Main() {
Array raw = new string[] { "a", "b", "c" };
raw.SetValue("X", 0);
Console.WriteLine(raw.GetValue(0));
}
}
Output
X
How It Works
No typed indexer. Variable type is Array.
SetValue writes. Index 0 becomes X.
GetValue reads. Confirms the change.
Type must match. Setting an int into string[] would throw.
Frequently Asked Questions
It writes a value into the array at the given index or indexes.
System.Array is non-generic. The runtime checks that the value fits the element type.
Yes. Pass one index per dimension after the value.
You get an exception such as InvalidCastException or ArgumentException.