Search code examples
c#access-modifiersc#-7.0local-functions

c# ERROR : The modifier 'private ' is not valid for this item


It doesn't matter what modifier I put on the front of the function(I've tried with public, private and even protected), I always receive an error, the same error. The code is clean only after I delete the modifier and I left the function "Array()" without one. Can someone look at my code and explain to me what is happening please, I am new to c#, and also new to asking help, so please excuse every mistake I've made so far.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            public void Array()//nu se pune in interiorul functiei void Main (), deoarece va forma nesting, si ne va da eroare la compilare.
            {
                int[] intArray;
                intArray = new int[3];//all values will be 3


                var doubleArray = new[] { 34.23, 10.2, 23.2 };

                //var arrayElement = doubleArray[0];
                //doubleArray[1] = 5.55;

                for (var i = 0; i < intArray.Length; i++)
                {
                    Console.WriteLine(intArray[i]);
                }
            }

        }



    }
}

I've posted the code and the image of it down below.

In this image you can see the code


Solution

  • You have a nested function, in C# these are called local functions and don't have scope. so you need to remove the access modifier, for example:

    public static void PrintHelloWorld()
    {
        string GetName()
        {
            return "world";
        }
    
    
        Console.WriteLine($"Hello {GetName()}");
    }