Question

I have the protected variable var1 in the abstract class AbstractModule

I create abstract class AbstractActivity : AbstractModule and use var1 from the parent class AbstractModule

Now I create class MyActivity : AbstractActivity and I want to make var1 not accessible in the MyActivity class.

How can I do it?

(I can create the protected property, but then I have the same problem)

Was it helpful?

Solution

C# does not allow this. But you can shadow the field in your class AbstractActivity by creating one with the same name. Your class MyActivity would then have access to the shadowed field and its value, but not to the field defined in AbstractModule.

  public class A
  {
     protected bool seeMe;
  }

  public class B : A
  {
     public B()
     {
        base.seeMe = false; // this is A.seeMe
     }

     protected bool seeMe;
  }

  public class C : B
  {
     public C()
     {
        seeMe = true; // this is B.seeMe
     }
  }

The above example doesn't prevent code from being written that uses the shadow field. This may cause confusion if the programmer is aware of A.seeMe and thinks it is being set. You can force a compile error when B.seeMe is used by decorating it with the Obsolete attribute:

  public class B : A
  {
     public B()
     {
        base.seeMe = false; // this is A.seeMe
     }

     [Obsolete("cannot use seeMe", error:true)]
     protected bool seeMe;
  }

  public class C : B
  {
     public C()
     {
        seeMe = true; // this will give a compile error
     }
  }

OTHER TIPS

Same example with above solutions with int value.
I trying to restrict grand parent field in child class with the same name.

  public class MyClass
  {
        protected int myValue = 10;
  }
  public class MyClass1 : MyClass
  {
        protected int myValue = 15;
        public MyClass1()
        {
            base.myValue = 25;
            this.myValue = 11;
        }
  }
  public class MyClass2 : MyClass1
  {
        public void print()
        {
            Console.WriteLine("My Value : " + myValue);//this will print 11                
        }
  }
  class Program
  {
        static void Main(string[] args)
        {
            MyClass2 myClass2 = new MyClass2();
            myClass2.print();
        }
  }

//Restrict grand parent method in child class using sealed keyword

public class MyClass
{
    protected virtual void MyMethod()
    {
    }
}
public class MyClass1 : MyClass
{
    // because of sealed method this method will not going to override in derived class.
    sealed override protected void MyMethod() 
    {
    }
}
public class MyClass2 : MyClass1
{
    protected override void MyMethod()//this will give compiler error
    {
    }  
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top