none
Private variable in method - C# RRS feed

  • Question

  • Hello,

    Why we cannot use private variable in methods?

    Thanks

     static void Main(string[] args)
            {
                private int a;
                List<Person> list = new List<Person>()
                {
                    new Person() { Entry = "Daniel"},
                    new Person() {ID = 10 , Entry = "Windows"}
                };
        }

    Saturday, February 8, 2020 9:06 PM

All replies

  • Access modifiers, such as "private" don't apply to local variables (variables declared within methods).  They only apply to types (classes, structs, enums, interfaces, and delegates) and type members (fields and methods).

    You can declare a private field at class level:

    class Test
    {
        private int a;
    
        static void Main(string[] args)
        {
        }
    }

    Or you can declare 'a' as a local variable:

    static void Main(string[] args)
    {
        int a;
    }
    



    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter

    Saturday, February 8, 2020 9:11 PM
  • You can use a private variable in a class, and a method or methods can use the private variable defined at the class level.

    If you want to define and use a variable at the local scope of a method, then you can use 'var'.

     lhttps://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var

    Saturday, February 8, 2020 9:16 PM
  • Why we cannot use private variable in methods?

    All variables declared in methods are private. Meaning that they cannot be seen from any code outside of the method. Since all of them are always private, you don't write the keyword "private" when you declare them.

    Saturday, February 8, 2020 10:28 PM
    Moderator
  • Hi Arash_89,

    Has your problem been solved?

    If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, February 20, 2020 8:12 AM
  • The variables whatever we define in methods, those variables access is limited to the respective methods itself. So it will not allow you to define the variables as private inside of methods in c#.

    To know more about access modifiers in c#, check 

    https://www.tutlane.com/tutorial/csharp/csharp-access-modifiers-public-private-protected-internal

    Thursday, February 20, 2020 11:19 AM