Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array issue c# "cannot apply indexing"

Tags:

arrays

c#

Potentially easy question here, I'm getting the error: Cannot apply indexing with [] to an expression of type 'System.Array'

    public Array hello()
    {
        var damn = new[] { a2,a3,a4,a5,a6,a7,a8,a9};
        return damn;
    }
    private void a1disable()
    {

        var a = new[] { a1, a2, a3, a4, a5, a6, a7, a8, a9 };
        var b = hello();

        a[1].Enabled = false;
        b[1].Enabled = false;
    }

a[1].Enabled = false; works absolutely fine! it's just b[1].Enabled = false; which throws the error i described above, i haven't used arrays much before so i'm sorry if the answer seems obvious, i'm just looking for clarification as to why this is happening. Thanks in advance if you can help :)

like image 839
Luke h Avatar asked Dec 08 '22 10:12

Luke h


2 Answers

All arrays derive from Array but Array is not indexable. Only concrete arrays are indexable. Without knowing the element type that the array has it is impossible getting a value out of it in a strongly typed way.

Make Hello return an int[] or whatever the right element type is.

like image 182
usr Avatar answered Dec 11 '22 08:12

usr


Array class does not have any indexer, you have to use the GetValue method, suppose the type of each element in b is TextBox, try this:

((TextBox) b.GetValue(1)).Enabled = false;

If you know the type of all elements beforehand, such as TextBox, why not just use the type TextBox[] as the return type of your hello() method?

public TextBox[] hello(){
  //....
}
//Then you can keep the old code.
like image 43
King King Avatar answered Dec 11 '22 08:12

King King