Compiler error · error CS0021
Cannot apply indexing with [] to an expression of type 'X'
Square brackets only work on things that hold multiple values in ordered slots. An int holds one number — there is no first element to ask for.
See it happen
int number = 2048;
Console.WriteLine(number[0]); // a single int has no elements
What IS indexable in C#
| Type | Index with | Example |
|---|---|---|
T[] array | int position | arr[0] |
string | int position → char | s[0] |
List<T> | int position | list[2] |
Dictionary<K,V> | a key | dict["k"] |
| your class, if it declares an indexer | whatever it accepts | obj[0] |
Fix 1: got a number, want its digits? Use a string
int number = 2048;
string digits = number.ToString(); // "2048"
Console.WriteLine(digits[0]); // '2' — indexing a string gives a char
Fix 2: or use arithmetic (the idiomatic way)
No indexing needed — % 10 peels the last digit and / 10 drops it:
int number = 2048;
int lastDigit = number % 10; // 8
Console.WriteLine(lastDigit);
Fix 3: you needed a collection but declared a scalar
int score = 90; // one value…
Console.WriteLine(score[0]); // …but indexing asks for a list
int[] scores = { 90 }; // now it really is a collection
Console.WriteLine(scores[0]);
Careful: two different errors look similar
| Code | When | Meaning |
|---|---|---|
CS0021 | compile time | The type has no indexer at all |
IndexOutOfRangeException | runtime | Indexer exists, but the position is past the end |
So a program can compile fine and still blow up at runtime — arr[10] on a 3-element array is valid syntax, invalid at run time. Guard with Length/Count.
Frequently asked
What does CS0021 mean?
You applied [] to a value that has no indexer. Only arrays, strings, List<T>, dictionaries, and classes that declare an indexer support it.
Why can't I index an int?
An int is a single number, not a collection of digits. Use n.ToString()[0] for a digit-character, or n % 10 arithmetic to peel digits.
Checklist
- Ask what the value actually is — a number, a string, a list, a dictionary?
- Numbers: no indexing. Use
.ToString()or arithmetic. - Strings: index gives a
char, not astring. - Dictionaries index by key, not by position.
- Confusing CS0021 with
IndexOutOfRangeException? The first is compile-time, the second runtime.