-1

i created an application depicting the protected access modifiers, using the sample provided on MSDN site, but it seems to be error prone, below is the code i am using:

Protected Access Modifier in c#

and below is the sample from MSDN site:

MSDN Reference for Protected Access Modifiers

Abbas
  • 4,948
  • 31
  • 95
  • 161

5 Answers5

2

Your AccessModifiersCSharp class which is where Main is defined does not inherit from Class1, so has no access to its protected members.

You can access Method1 from your Class2 as it does inherit from Class1.

The difference between your code and the MSDN code is that class B that contains Main inherits directly from A.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

protected members of class A can only be accessed from classes derived from A.

This means Class2 can access Method1(), but not AccessModifiersCSharp

see msdn

If you want your code to compile, you need to declare Method1() as public or internal.

Louis Kottmann
  • 16,268
  • 4
  • 64
  • 88
0

Put the Main() method inside Class2 instead of the class AccessModifiersCSharp! The AccessModifiersCSharp does not derive from Class1 and thus has no access to its protected members and methods.

Abbas
  • 14,186
  • 6
  • 41
  • 72
0

In the article that you referenced, Main is a method of B, which is why it has access to protected members of B, and, through inheritance, A's protected members.

Tung
  • 5,334
  • 1
  • 34
  • 41
0

A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member

it's mean: you can access Methode1 in Class1 methods And Class2 Methods. and You can access Method2 only in Class2 methods.

Main() Method in AccessModifiersCSharp class. and only can access to public method of Class1 and Class2.

Morteza
  • 2,378
  • 5
  • 26
  • 37