0

I am pretty new to lambda expressions and am trying to write a simple program here to understand the use of Func<> and can't understand why I cannot loop through an input array using indexing?

class Program
{
    static void Main(string[] args)
    {
        int[] array = new int[4];
        array[0] = -1; array[1] = 2; array[2] = 3; array[3] = 8;

        Func<Array, int> DoSomething = inputarray =>
        {
            for (int i = 0; i < inputarray.Length; i++)
            {
                if (inputarray[i] > inputarray[i + 1])
                {
                    //;
                }

            }
            return 1;
        };

    }
}

This gives an error saying

cannot apply indexing with [] to an expression of type Array

How do I resolve this? Basically, how would I loop through my input array?

3
  • Change Array in Func<> to int[] or do you van to have an option that it will except all kinds of arrays Commented May 18, 2017 at 7:44
  • Works..!!! But what was wrong with type Array?? Is it because arrays do not have indexers?? idk Commented May 18, 2017 at 7:45
  • 3
    I think Array refers to System.Array which is not exactly an array. Commented May 18, 2017 at 7:45

2 Answers 2

1

A System.Array is the base class of all arrays like an int[]. It implements also IList which allows to access items by index, but the Item property is implemented as an explicit interface member implementation. It can be used only when the Array instance is cast to an IList interface:

var list = (System.Collections.IList)inputarray;

Now you can use the indexer but it will return objects not ints, so you can't use following without casting because objects can't be compared with >:

if (list[i] > list[i + 1])
{
    //;
}

I guess you want to use an int[]:

Func<int[], int> DoSomething = inputarray =>
// ...
Sign up to request clarification or add additional context in comments.

Comments

1

You need to provide a type for the Array in the example you show.

try:

Func<int[], int> DoSomething

instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.