-3

How can we restrict the class variable to not to inherit or change the value in derived class?

ex-

Class A
{
   public string name="ABC";
}
Class B:A
{
   //I don't want here name property of base class should be accessible  
     or can be changed  
}
user2147163
  • 87
  • 1
  • 4
  • 13
  • 2
    make your public field to private – Bhuban Shrestha Jun 20 '17 at 12:31
  • Hi @BhubanShrestha but isn't true private members are accessible in derived class – user2147163 Jun 20 '17 at 12:33
  • Possible duplicate of [How to hide an inherited property in a class without modifying the inherited class (base class)?](https://stackoverflow.com/questions/1875401/how-to-hide-an-inherited-property-in-a-class-without-modifying-the-inherited-cla) – Balagurunathan Marimuthu Jun 20 '17 at 12:33
  • If you don't want the value changed at any time you can make it a constant. – PaulF Jun 20 '17 at 12:33
  • Just make it private: `private string name="ABC";`. That way it can only be accessed via `A`. – David Arno Jun 20 '17 at 12:33
  • 3
    Private members are not accessible in descendant types, other than using reflection (and having the access to do so), but all code can use reflection in that case. So `private` is what you want. If by "not to inherit" means "doesn't see the field at all", private is what you want. If you only want to restrict modifications, create a property with a public/protected getter and a private setter. – Lasse V. Karlsen Jun 20 '17 at 12:37
  • 2
    However, you can't make B not *have* that field, it will still be there in the memory layout of B, simply because the field is still inherited from A. By making it private you remove access to it, you don't remove the field. – Lasse V. Karlsen Jun 20 '17 at 12:39

1 Answers1

3

You could make use of property with private set as follows:

class A
{ 
    public string Name
     {
       get;
       private set;
     } 
}

class B:A 
{ 
   public B()
    {
      this.Name = "Derived"; // This will not work. If you want to prevent the derived class from accessing the field, just mark the field as private instead of public.
    }
}
ashin
  • 2,543
  • 1
  • 12
  • 17