Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inaccessible due to its protection level?

Tags:

c#

constructor

I'm still quite new to coding in general, and while this simple program is only meant to be a test to learn how constructors work, I'd still like to know why I'm getting this error.

    using System;

    public class methodTest
    {
        int a;
        int b;
        int c;
         public methodTest(int i, int j, int k)
        {
            a = i;
            b = j;
            c = k;
        }
    }

    public class methodObj
    {
        static void Main()
        {
        methodTest obj = new methodTest(10, 20, 30);
        Console.WriteLine("obj = " + obj.b);
        Console.ReadKey();
        }
    }

I'm not entirely sure why I'm getting the error. The problem is with the Console.WriteLine, where it states it cannot access obj.b. The variables seem to be declared within a public class, so why can they not be accessed? I tried searching for a solution to this, but all the questions I found were much too convoluted for me to get an answer I could translate to my own understanding. All help appreciated!

like image 466
Forumpy Avatar asked Jul 08 '15 20:07

Forumpy


2 Answers

Even though the variables are in a public class, they must be declared as public as they are private by default.

See: Access Modifiers

Class members, including nested classes and structs, can be public, protected internal, protected, internal, or private. The access level for class members and struct members, including nested classes and structs, is private by default.

It is best practice to use capitalized names and properties for public variables.

public A { get; set; }

Properties allow you to control the access of reading/writing of the member, as well as adding logic when they are read or set.

like image 144
Cyral Avatar answered Sep 28 '22 01:09

Cyral


Access modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the four access modifiers:

The following five accessibility levels can be specified using the access modifiers:

  1. public : Access is not restricted.
  2. protected : Access is limited to the containing class or types derived from the containing class.
  3. Internal : Access is limited to the current assembly.
  4. protected internal: Access is limited to the current assembly or types derived from the containing class.
  5. private : Access is limited to the containing type.

Every members in C# are implicitly private, so in your question the a,b and c are defined as private and so you could not access to them from outside of methodTest. for more information you may need to look at this page : Access Modifiers (C# Programming Guide)

Good Luck! :)

like image 42
Ali Adlavaran Avatar answered Sep 28 '22 01:09

Ali Adlavaran