Posted by: Amit Andharia | January 3, 2009

Protected Access Modifier

The protected keyword is a member access modifier. A protected member is accessible within its class and by derived classes.

A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. For example, consider the following code segment:

using System;
class B

protected int x = 123; 

}

class D : B
{

 static void Main()
 {

  B b = new B();
  D d = new D();

  // Error CS1540, because x can only be accessed by
  // classes derived from B.
  // b.x = 10;

  // OK, because this class derives from B.
  d.x = 10;

 }

}

The statement b.x =10 generates an error because B is not derived from D.

Struct members cannot be protected because the struct cannot be inherited.

Example:
In this example, the class DerivedLocation is derived from Location; therefore, you can access the protected members of the base class directly from the derived class.

using System;
class Location
{

protected int x;
protected int y;

}
class DerivedLocation: Location
{

static void Main()
{

DerivedLocation dlocation = new DerivedLocation();

// Direct access to protected members:
dlocation.x = 10;
dlocation.y = 15;
Console.WriteLine(“x = {0}, y = {1}”, dlocation.x, dlocation.y);

}

}

Output:
x = 10, y = 15

Advertisements

Responses

  1. […] modifier: A keyword, such as private, protected, internal, or public, that restricts access to a type or type […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: