Search code examples
c#oopaccess-modifiers

classes and access modifiers in .net


I have 3 Questions regarding Oops Concepts:

  1. What is the default access modifiers for class in the namespace, i tried to apply modifiers to the class, .net compiler threw error saying `Elements defined in namespace cannot be explicity declared as private, protected or protected friends. below is my code. Access Modifiers for the class in c#

  2. What is the difference between protected internal and internal as internal could be used within the assembly, and protected internal could be used in the same class, inherited class or the other classes within the same assembly. and basically what exactly here meant by assembly.

  3. If there is 2 class Class1 and Class2 Class1 has Method1() and Class2 has Method2(), if both are in the inherit chain, then Class1 c = new Class2(); shall allow to access Method2(); because here the new object is of Class2 then why .net allows Method1(); i tried this.

Solution

  • 1) Internal

    2) Either a derived class (potentially in a different assembly) or any code in the same assembly can access

    3) You have a reference to a class1 which doesn't have method2 - you need a reference to a class2 to be able to call method2.