Cannot apply indexing with [] to an expression of type 'System.Array' with C#
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[]>();
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();
You should not use the type Array
in your code, so change your
public List<Array> alphabet = new List<Array>();
into e.g.
public List<string[]> alphabet = new List<string[]>();
or
public List<List<string>> alphabet = new List<List<string>>();
If you stick to Array
for some reason, you cannot use expr[i]
but will have to do expr.GetValue(i)
, but I discourage it because the declared return type is object
, and you will end up with a lot of casting.