0

I want to create a filtered array with LINQ inside the function I created and print it on the screen. I got some errors.

    static void Main(string[] args)
    {
        //created an integer array
        var values = new[] {2,9,5,0,3,7,1,4,8,5 };

        // display original values
        Console.WriteLine("Orijinal Dizi:");
        foreach (var element in values)
        {
            Console.WriteLine($"{element}");
        }

        FilteredArray(values);
        
    }
    public void FilteredArray(int[] values)
    {
        var filtered =
            from value in values
            where value > 4
            select value;
        Console.WriteLine("4ten büyükleri filtreleyen dizi");
        foreach (var item in filtered)
        {
            Console.WriteLine($"{item}");
        }
    }

"FilteredArray (values);" is underlined in red. Error CS0120: An object reference is required for the non-static field, method, or property 'Program.FilteredArray(int[])'

  • 2
    `Main` is a static Method, where as `FilteredArray` is not. Just change `FilteredArray` to static (ie `public static void FilteredArray(int[] values)`) –  May 02 '21 at 11:16

2 Answers2

3

Change the FilteredArray signature to be static.

Amit Bisht
  • 4,870
  • 14
  • 54
  • 83
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
0

Main is a static method so FilteredArray must be static too:

public static void FilteredArray(int[] values)
tymtam
  • 31,798
  • 8
  • 86
  • 126
  • In fairness, it *must not* necessarily be static. Assuming OP is using the normal project scaffolding, something such as `new Program().FilteredArray()` *could* also work. Though I admit this detail is lacking in the OP but the choice of the word "must" could give a new developer the impression they might never be able to call an instance method from a static one – pinkfloydx33 May 02 '21 at 13:14