Arrao4u

…a blog by Rama Rao

Archive for the ‘AccessModifiers’ Category

Access Modifiers

Posted by arrao4u on March 6, 2011

Introduction

Access modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the four access modifiers:

  • public (No restrictions to access).
  • protected (Access is limited to within the class definition and any class that inherits from the class).
  • internal (Access is limited exclusively to classes defined within the current project assembly).
  • private (Access is limited to within the class definition; This is the default access modifier type if none is formally specified).

 

The access modifiers in .NET are

1. public

2. private

3. protected

4. internal

5. protected internal

public

Public means visible to everyone and everywhere.

Access cases

1. By objects of the class

2. By derived classes

Example: In the following example num1 is direct access.

using System;

namespace AccessModifiers

{

    class Program

    {

        class AccessMod

        {

            public int num1;

        }

        static void Main(string[] args)

        {

            AccessMod ob1 = new AccessMod();

            //Direct access to public members

            ob1.num1 = 100;

            Console.WriteLine(“Number one value in main {0}”, ob1.num1);

            Console.ReadLine();

        }

    }

}

Example 2:

[public]

(No restrictions to access – methods are open for anyone to see)

The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members.

Example

In the following example, two classes are declared, CClass1 and CClass2. The public members x and y of the CClass1 are accessed directly from CClass2.

// protected_public.cs
// Public access
using System;
class CClass1
{
   public int x;
   public int y;
}

class CClass2
{
   public static void Main()
   {
      CClass1 CC = new CClass1();

      // here is direct access to public members:
      CC.x = 3;
      CC.y = 5;
      Console.WriteLine(“x = {0}, y = {1}”, CC.x, CC.y);
   }
}

Output

x = 3, y = 5

If you want to change the public access level to private or protected, you will get the error message:

'CClass1.y' is inaccessible due to its protection level.

 

public:

The public access specifier in C# allows a class to expose its member variables and member functions to other functions and objects. So any member declared public can be accessed outside the class also.

Let’s check an example for this..
—————————————————————-

using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
}
class MyMainClass
{
static void Main(string[] args)
{
hello HelloObject=new hello();
HelloObject.iNum1=10; /* since variable iNum1 is public it can be accessed in other classes also*/

Console.WriteLine(HelloObject.iNum1);
}
}
}

private

Private means hidden and usable only by the class itself. No code using a class instance can access a private member and neither can a derived class. Information or functionality that will not be needed or has no meaning outside of the context of a specific class should be made private.

Access cases

1. Cannot be accessed by object

2. Cannot be accessed by derived classes

Example: In the following example num2 is not accessible outside the class.

using System;

namespace AccessModifiers

{

    class Program

    {

        class AccessMod

        {

            public int num1;

            int num2;

        }

        static void Main(string[] args)

        {

            AccessMod ob1 = new AccessMod();

            //Direct access to public members

            ob1.num1 = 100;

            //Access to private member is not permitted

            ob1.num2 = 20;

            Console.WriteLine(“Number one value in main {0}”, ob1.num1);

            Console.ReadLine();

        }

    }

}

The above program will give compilation error, as access to private is not permissible. In the below figure you can see the private member num2 is not available.
 

 

 
 
 

 

[private]- (Access is limited to within the class definition)

The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared.

Nested types in the same body can also access those private members.

It is a compile-time error to reference a private member outside the class or the struct in which it is declared.

Example

In this example, the Emp class contains a public member, Name, and a private member, Salary. The public member can be accessed directly, while the private member must be accessed through the public method GetSalary().

// private_keyword.cs
using System;
class Emp
{
   public string name = "xx";
   double salary = 100.00;   // private access by default
   public double GetSalary() {
      return salary;
   }
}

class MainClass
{
   public static void Main()
   {
      Emp e = new Emp();

      // Accessing the public field:
      string n = e.name; 

      // Accessing the private field:
      double s = e.GetSalary();   
   }
}

In the preceding example, if you attempt to access the private members directly by using a statement like this:

double s = e.salary;

you will get the error message:

Emp.Salary' is inaccessible due to its protection level.

 

private:

The private access specifier in C# is just opposite to the public access specifier. That is it allows a class to hide its member variables and member functions from other class objects and functions. So it is not visible outside the class. By default, the access specifier is private; if public, private or protected is not specified.

Let’s check an example for this..
—————————————————————-

using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
private int iNum2;

public hello()
{
iNum1=0;
iNum2=10;
}
}

class MyMainClass
{
static void Main(string[] args)
{
hello HelloObject=new hello();
//CORRECT METHOD
HelloObject.iNum1=10; //Here since variable iNum1 is public it can be accessed in other classes also

//WRONG METHOD
HelloObject.iNum2=20; /*This line will return an Error since the access to this variable is Private. So it cannot be accessed outside the class*/

Console.WriteLine(HelloObject.iNum1);
}
}
}

—————————————————————-

protected

Protected members are similar to private ones in that they are accessible only by the containing class. However, protected members also may be used by a descendant class. So members that are likely to be needed by a descendant class should be marked protected.

Access cases

1. Cannot be accessed by object

2. By derived classes

protected  

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.

A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.

Accessibility: 

  • Cannot be accessed by object
  • By derived classes

 

using System;

namespace AccessModifiers

{

    class Program

    {

        class Base

        {

            protected int num1;

        }

        class Derived : Base

        {

            public int num2;

            static void Main(string[] args)

            {

                Base ob1 = new Base();

                Derived ob2 = new Derived();

                ob2.num1 = 20;

                // Access to protected member as it is inhertited by the Derived class

                ob2.num2 = 90;

                Console.WriteLine(“Number2 value {0}”, ob2.num2);

                Console.WriteLine(“Number1 value which is protected {0}”, ob2.num1);

                Console.ReadLine();

            }

        }

    }

}

In the above program we try to access protected member in main it is not available as shown in the picture below that num1 is not listed in intellisense.

[protected]The protected keyword is a member access modifier.
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.

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:

class XX
{
   protected int x = 111;
}

class YY : XX
{
   void F()
   {
      XX a = new XX(); 
      YY b = new YY(); 
      a.x = 7;   // Will give an error
      b.x = 7;   // OK
   }
}

The statement a.x=7 generates an error because XX is not derived from YY.

Note: “Struct members cannot be protected because the struct cannot be inherited.”

It is an error to reference a protected member from a class, which is not derived from the protected member’s class.

Example

In this example, the class DerivedClass is derived from CClass; therefore, you can access the protected members of the base class directly from the derived class.

// protected_keyword.cs
using System;
class CClass
{
   protected int a;
   protected int b;
}

class DerivedClass: CClass
{
   public static void Main()
   {
      DerivedClass dC = new DerivedClass();

      //here is direct access to protected members:
      dC.a = 3;
      dC.b = 5;
      Console.WriteLine("a = {0}, b = {1}", dC.a, dC.b);
   }
}

Output

a = 3, b = 5

If you change the access levels of x and y to private, the compiler will issue the error messages:

'CClass.a' is inaccessible due to its protection level.
'CClass.b' is inaccessible due to its protection level.

 

public class Base
{
    protected int Var1;
    internal int Var2;
}

public class Derived : Base
{
    public void MyMethod()
    {
        // Bot Members are inherited
        Var1 = “Value”;
        Var2 = “Value”;
    }
}

public class Unrelated
{
    public void MyMethod()
    {
        Base B = new Base();
        B.Var1 = “Value”;    // Compile Error (Var1 cannot be accessed from this class)
        B.Var2 = “Value”;
    }
}

The above code contains three classes: Base which declares two variables and is the base class for class Derived. A third class Unrelated exists in the same assembly. As you can see, Var1 and Var2 get inherited to the Derived class. As such, they are directly usable by a method of the class. Class Unrelated is not derived from class Base. It can however, access the members of class base by creating an object of it. internal members being public for the assembly are accessible through the Unrelated class. But, the protected variable Var1 is not accessible because Unrelated is not derived from class Base or any of its child classes.

protected:

The protected access specifier in C# allows a class to hide its member variables and member functions from other class objects and functions, except the child class. This access specifier is used when we need to use Inheritance in the program.

Let’s check an example for this..
—————————————————————-

using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
protected int iNum2;
}

class world : hello
{
public int AddDetails()
{
iNum1=20;
iNum2=10;

return iNum1+iNum2;
}
}

class MyMainClass
{
static void Main(string[] args)
{
world worldObject=new world();

worldObject.iNum1=50; //Line 1 No Error

worldObject.iNum2=10; //Line 2 Error

Console.WriteLine(worldObject.AddDetails().ToString());

}
}
}

—————————————————————-
In the above case we have not called the object of the class hello. But we have inherited the class hello to the class world. So all the public and protected members inside the class is accessible inside the derived class also. We don’t need to create objects for the base class to access the variables or methods we have in our parent class.
Now inside the Main() function we are assigning value to iNum1 and iNum2. Line 1 will not return any error because the variable iNum1 is public. So, it can be accessed from anywhere in the program, but Line2 will give an Compilation Error saying “iNum2 is inaccessible due to protection level”. This is because access of the variable iNum2 is set to protected. The protected members can only be accessed inside the Child class and its parent class.

internal

Internal are public to the entire assembly but private to any outside assemblies. Internal is useful when you don’t want to allow other assemblies to have the functionality.

Access cases

In same assembly (public).

1. By objects of the class

2. By derived classes

In other assembly (internal)

1. Cannot be accessed by object

2. Cannot be accessed by derived classes

d) Internal/Friend: Publicly accessible by all the members of the assembly.
e) Protected Internal/Protected Friend: Members of the assembly and derived class can access.

internal  

The internal keyword is an access modifier for types and type members. We can declare a class as internal or its member as internal. Internal members are accessible only within files in the same assembly (.dll).

In other words, access is limited exclusively to classes defined within the current project assembly.

Accessibility:  

In same assembly (public) 

  • Can be accessed by objects of the class
  • Can be accessed by derived classes

 

In other assembly (internal) 

  • Cannot be accessed by object
  • Cannot be accessed by derived classes
  • [internal]
  • A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.
  • It is an error to reference a member with internal access outside the assembly within which it was defined.
  • Note: An internal virtual method can be overridden in some languages, such as textual Microsoft intermediate language (MSIL) using Ilasm.exe, even though it cannot be overridden using C#.
  • This example contains two files, Assembly1.cs and Assembly2.cs. The first file contains an internal base class, BaseClass. In the second file, an attempt to access the member of the base class will produce an error.
  • File Assembly1.cs:
  • File Assembly2.cs
  • The internal keyword is an access modifier for types and type members. Internal members are accessible only within files in the same assembly.

·         Example

·         // Assembly1.cs
·         // compile with: /target:library
·         internal class BaseClass
·         {
·         public static int IntM = 0;
·         }
·         // Assembly2.cs
·         // compile with: /reference:Assembly1.dll
·         // CS0122 expected
·         class TestAccess
·         {
·            public static void Main()
·            {
·               BaseClass myBase = new BaseClass();   // error, BaseClass not visible outside assembly
·            }
·         }

internal:

The internal access specifier in C# allows a class to expose its member variables and member functions to other function and objects. It can be accessed from any class or method defined with the application in which the member is defined. The default access specifier is internal for a class

protected internal

Finally, we have the only compound access modifier allowed in .NET. Members marked as protected internal may be accessed only by a descendant class that’s contained in the same assembly as its base class. You use protected internal in situations where you want to deny access to parts of a class’ functionality to any descendant classes found in other applications.

Note: that it’s illegal to combine two access modifiers for a class but can only be applied to the members.

Access cases

In same assembly (protected).

1. Cannot be accessed by object

2. Can be accessed by a derived classes

In other assembly (internal)

1. Cannot be accessed by object

2. Cannot be accessed by derived classes

protected internal  

The protected internal accessibility means protected OR internal, not protected AND internal.

In other words, a protected internal member is accessible from any class in the same assembly, including derived classes.

The protected internal access modifier seems to be a confusing but is a union of protected and internal in terms of providing access but not restricting. It allows:  

  • Inherited types, even though they belong to a different assembly, have access to the protected internal members.
  • Types that reside in the same assembly, even if they are not derived from the type, also have access to the protected internal members.

 

protected internal:

The protected internal access specifier in C# allows methods or member variables accessible to a class and its derived classes inside the same assembly or namespace within a file. These members cannot be accessed from class inside another assembly or a file.

Lets now understand the above with an example:
—————————————————————-
using System;
class Student
{
private string sAddress;
protected string sPhNo;
protected internal long iZipCode;
void Hello()
{
Console.WriteLine(“Hello World!”);
}
internal void Hello2()
{
Console.WriteLine(“Hello Student!”);
}
public void SetAddress()
{
Console.WriteLine(“Enter your Address:”)
sAddress = Console.ReadLine();
}
public void SetPhNo()
{
Console.WriteLine(“Enter your Phone Number:”)
sPhNo = Console.ReadLine();
}
public void SetZipCode()
{
Console.WriteLine(“Enter the Zip Code: “);
iZipCode =Convert.ToInt64(Console.ReadLine());
}
public void DisplayStudent()
{
Console.WriteLine(“The Address is: {0}”, sAddress);
}
}
class Display
{
static void Main(string[] args)
{
Student John = new Student();
Console.WriteLine(John.sAddress); //Error: protected members cannot be accessed
John.SetAddress(); //public members can be accessed outside the class definition
John.SetPhNo(); //public members can be accessed outside the class definition
Console.WriteLine(John.sPhNo); //error: protected internal members cannot be accessed outside the class definition
John.SetZipCode(); //public members can be accessed outside the class definition
John.DisplayStudent(); // public members can be accessed outside the class definition
Console.WriteLine(John.sAddress); //error: private members cannot be accessed outside the class definition
John.Hello(); //error: private members cannot be accessed outside the class definition
John.Hello2(); //displays Hello student!
Console.ReadLine();

Default access

 

A default access level is used if no access modifier is specified in a member declaration. The following list defines the default access modifier for certain C# types:

enum: The default and only access modifier supported is public.

class: The default access for a class is private. It may be explicitly defined using any of the access modifiers.

interface: The default and only access modifier supported is public.

struct: The default access is private with public and internal supported as well.

The default access may suffice for a given situation, but you should specify the access modifier you want to use to ensure proper application behavior.

Note: Interface and enumeration members are always public and no access modifiers are allowed.

Point to remember

Interface and enumeration members are always public and no access modifiers are needed (or allowed).

Classes in namespaces are internal by default and may be either internal or public but cannot be private or protected, while namespaces themselves are always public.

Members of a struct are private by default and may be given public, internal, or private access modifiers.

To summarize it

Code:

+——————+———+———–+——–+———-+——————–+

|                  | private | protected | public | internal | protected internal |

+——————+———+———–+——–+———-+——————–+

| By object        | No      | No        | Yes    | Yes      | No                 |

+——————+———+———–+——–+———-+——————–+

| By derived class | No      | Yes       | Yes    | Yes      | Yes(Same assembly) |

+——————+———+———–+——–+———-+——————–+

 

Summary:

 

Interface and enumeration members are always public and no access modifiers are needed (or allowed).

Classes in namespaces are internal by default and may be either internal or public but cannot be private or protected, while namespaces themselves are always public.

Members of a struct are private by default and may be given public, internal, or private access modifiers.

To summarize it:

  private protected public internal protected internal
By object No No Yes Yes No
By derived class No Yes Yes Yes Yes(Same assembly)

 

Protected Internal:

If you want a member to be accessible only by the class containing it or its derived class which belongs to the same assembly in which the class is put up, then you have to use protected internal access modifier.

To demonstrate it, follow the steps shown below:

• Create the following class:
public class sampleClass {
protected internal int member1;
}

• Name the class as sampleAssembly.cs and Compile this class by specifying /target:library

• Create a new program called testClass.cs with the following code:
public class testClass:sampleClass {
public static void Main() {
member1 = 10;
}
}

• Compile this program by specifying /reference:sampleAssembly.dll

• Now try to execute testClass. You will end up in the following error:

“‘sampleClass.member1’ not visible outside assembly”

This is because, you try to access protected internal member of sampleClass from its derived class which is referencing the assembly but not belonging to that assembly. If the testClass is also part of sampleAssembly then you can very well access member1 without any errors.

Note that protected internal access modifier should not be used as a modifier on a class. If you try to use it, then you will end up in the following error: “Namespace elements cannot be explicitly declared as private, protected, or protected internal”

Posted in AccessModifiers, C# | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.