Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot apply indexing with [] to an expression of type 'System.Array' with C#

Tags:

I'm trying to use a List containing string arrays, but when I attempt to access the array elements using square brackets, I receive an error.

My List of arrays is declared like this:

public List<Array> alphabet = new List<Array>(); 

I also have a string array declared like this:

 string[] encrypted = new string[text.Length]; 

I am able to access one array, but not the other

string a = alphabet[1][2]; // this gives me an error  string b = encrypted[1]; // this works fine 
like image 525
W1k3 Avatar asked May 11 '14 18:05

W1k3


2 Answers

The Error is pretty straightforward; you can't use an indexer on an Array. Array class is a base class for all array types, and arrays are implicitly inherit from Array. But, Array itself doesn't have an indexer. Here is a demonstration of your error:

int[] numbers = new[] {1, 2, 3, 4, 5};  numbers[2] = 11; // Okay  Array arr = numbers as Array;  arr[2] = 11; // ERROR! 

So if you want to use the indexer, change your element type to an array of something for example:

public List<string[]> alphabet = new List<string[]>(); 
like image 164
Selman Genç Avatar answered Oct 19 '22 15:10

Selman Genç


Try using .ElementAt. It works on anything that implements IEnumerable, including collections that aren't indexed.

MSDN reference.

I've split your statement up into multiple statements so it's easier to identify the offending line.

Please note - ElementAt is an extension method and you will need to be using the System.Linq namespace to use it.

using System.Linq; 

Then in your method:

var n = getnumber(text.ElementAt(i));  var items = alphabet.ElementAt(n);  encrypted[i] = items.ElementAt(symnumb).ToString(); 
like image 39
PeteGO Avatar answered Oct 19 '22 15:10

PeteGO