Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Protected method in base class; unable to access using derived class object from another class

Protected members of a base class should be accessible to a class which inherits from base class right?

I'm trying to access protected method of base class using a object of derived class from another class but i get the a error message saying is "the base class method is inaccessible due to protection level".

can anyone help me understand what is it that i'm doing wrong

Program.cs

    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass dc = new DerivedClass();
            dc.DisplayValue();

        }
    }

BaseClass.cs

    class BaseClass
    {
        private int value = 3;

        protected void DisplayValue()
        {
            Console.WriteLine(this.value);
        }
    }

DerivedClass.cs

    class DerivedClass : BaseClass{}

1 Answer

Steven Parker
Steven Parker
229,732 Points

You can access a protected method from within the derived class.

But here, you're trying to access it from Main. Yes, you're using an instance of the derived class, but the access is not from within that derived class.

Is how "protected" interpreted in C# different from Java. The above code is possible in java as long as i'm using the object of derived class

Steven Parker
Steven Parker
229,732 Points

I can't speak for Java

But I can tell you that the C# behavior of protected members is consistent with C++ behavior.

I've been told that the concept of "protected" in Java might not be on the class level, but may be on the "package" level — that would certainly be different.

But in any case, languages are unique in their own ways, so you just need to learn the "C# way".

Seth Kroger
Seth Kroger
56,413 Points

In Java protected means it can be accessed from any subclass or from within the same package. If you have your Main class in the same package as the others, which would be common for small examples/programs, then you'd be able to access it.