Define different Access modifiers in C#

 Posted by Poster on 10/29/2010 | Category: C# Interview questions | Views: 8722 | Points: 40

The access modifier is the key of Object Oriented Programming, to promote encapsulation, a type in C# should limit its accessibility and this accessibility limit are specified using Access modifiers.

They are - Public, Internal, Protected, Private, Protected Internal

When used that type (method or variable) can be used by any code throughout the project without any limitation. This is the widest access given to any type and we should use it very judiciously. By default, enumerations and interface has this accessibility.

When used that type can be used only within the assembly or a friend assembly (provided accessibility is specified using InternalVisibleTo attribute). Here assembly means a .dll.
For example if you have a .dll for a Data Access Layer project and you have declared a method as internal, you will not be able to use that method in the business access layer)
Similarly, if you have a website (not web application) and you have declared internal method in a class file under App_Code then you will not be able to use that method to another class as all classes in website is compiled as a separate .dll when first time it is called).

Internal is more limited than Public.

When used that type will be visible only within that type or sub type. For example, if you have a aspx page and you want to declare a variable in the code behind and use it in aspx paeg, you will need to declare that variable as at least protected (private will not work) as code behind file is inherited (subclass) by the aspx page.

Protected is more secure than Internal.

When used that type will be visible only within containing type. Default access modifier for methods, variables. For example, if you have declared a variable inside a method, that will be a private variable and may not be accessible outside that method.

Private is the most secure modifiers than any other access modifiers as it is not accessible outside.

Protected Internal
This is not a different type of access modifiers but union of protected and internal. When used this type will be accessible within class or subclass and within the assembly.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response