Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 5 years ago.
I'm trying to use a List containing string arrays in C# but I don't know how to format my declaration properly.
private String encrypt(char[] text)
{
Random rnd = new Random();
string[] encrypted = new string[text.Length];
for (int i = 0; i < text.Length; i++)
{
int symnumb = rnd.Next(listmin, listmax);
encrypted[i] = alphabet[getnumber(text[i])][symnumb].ToString();
}
return string.Join("", encrypted);
}
This is further down:
private int getnumber(char letter)
{
for (int i = 0; i < 27; i++)
{
if (letter == alphabetc[i])
{
return i;
}
}
return -1;
}
I have to much irrelevant code to post it all, but "encrypted" is a string array, "alphabet" is a list of arrays containing strings.
Declarations:
public List<Array> alphabet = new List<Array>();
public char[] alphabetc = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '};
Any help would be great.
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.