Home > Software design >  Preventing Access Public Member of Base Class From Derived Class in C#
Preventing Access Public Member of Base Class From Derived Class in C#

Time:09-26

Is this possible to preventing access public member (such as method, variable etc.) of base class from derived class instance? For example;

public class BaseClass
{
    public int m_a;
}

public class DerivedClass : BaseClass
{
    base.m_a = 10; //good
}

but, I don't want to this;

DerivedClass dc = new DerivedClass();
dc.m_a = 20; //not good

Is that possible?

CodePudding user response:

protected means the derived class can access it, however, the derived class can access the property of it's own instance also.

       static void Main(string[] args)
        {
            BaseClass bc = new BaseClass();
            DerivedClass dc = new DerivedClass();
           
           
            dc.doSomething(); //set value of baseClass from DerivedClass

            // dc.m_a = 20; //'Program.BaseClass.m_a' is inaccessible due to its protection level
            // bc.m_a = 20; //'Program.BaseClass.m_a' is inaccessible due to its protection level


            Console.WriteLine("Hello World!");
        }

       
        class BaseClass {
            protected int m_a;

            public void setValue(int m_a) {
                this.m_a = m_a;
            }
        }

        class DerivedClass : BaseClass {
            BaseClass baseClass = new BaseClass();
           
            public void doSomething() {
                this.m_a = 5;          // valid. You are accessing your own variable
                //baseClass.m_a = 5;   // invalid. You are attempting to access the protected property externally
                baseClass.setValue(5); // valid. Using a public setter
            }
        }

CodePudding user response:

Unfortunately, the base class is a .net class. Because of this, I can not use any modifier for base class.

CodePudding user response:

try this

public static void Main()
{
DerivedClass dc = new DerivedClass();
dc.m_a = 20; // ERROR!

}


public class BaseClass
{
    protected int m_a;
}

public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
        m_a=20; //No Error
    }
}

  • Related