Access Specifiers in C#

What are Access Specifiers in C#?

Access specifiers in C# are keywords that control the visibility of classes, members, and types. They allow you to restrict access to certain parts of your code, which can help to improve the security and maintainability of your code.

Types of Access Specifiers
  • Public: Public members are accessible to all code in the assembly in which they are defined, as well as any code that references that assembly.
  • Private: Private members are only accessible to code within the class in which they are defined.
  • Protected: Protected members are accessible to code within the class in which they are defined, as well as any types that are derived from that class.
  • Internal: Internal members are accessible to all code in the assembly in which they are defined.
  • Protected Internal: Protected internal members are accessible to code within the assembly in which they are defined, as well as any types that are derived from the class in which they are defined.
Syntax:

The general syntax for access specifiers in C# is:

access_specifier member_type member_name;

Where:

  • access_specifier is one of the five access specifiers (public, private, protected, internal, protected internal).
  • member_type represents the data type or return type of the member.
  • member_name is the name of the class member.

Here is a table that shows examples of how to use each access specifier:

Access specifier Example
public public string name;
private private int age { get; set; }
protected protected void CalculateSalary(decimal salary) { … }
internal internal class MyClass { … }
protected internal protected internal interface IMyInterface { … }
Usage of Access Specifiers
  • Access specifiers in C# control the visibility and accessibility of class members.
  • They promote encapsulation and data security.
  • Access specifiers define what parts of the code can be accessed by other classes or code outside the current class.
  • Proper use of access specifiers ensures a clean and manageable interface for users and enhances code organization and security.

Example 1:
The following examples show how to use access specifiers to control access to fields, properties, and methods:

// Public field
public string name;
 
// Private property
private int age { get; set; }
 
// Protected method
protected void CalculateSalary(decimal salary)
{
    // ...
}
  • The name field is public, so it can be accessed by any code in the assembly.
  • The age property is private, so it can only be accessed by code within the class in which it is defined.
  • The CalculateSalary() method is protected, so it can be accessed by code within the class in which it is defined, as well as any types that are derived from that class.

Example 2:
The following example shows how to use access specifiers to control access to a member:

advertisement
advertisement
public class Customer
{
    private string _name;
 
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
}
  • The _name field is private, so it can only be accessed by code within the Customer class.
  • The Name property provides public access to the _name field.
  • This example shows how to use private access specifiers to hide the implementation details of a class from other code. This can make the code more difficult to misuse and easier to maintain.
Difference between Modifiers and Access Specifiers

Modifiers change the behavior of a member, such as making it virtual or abstract. Access specifiers control who can access a member.

For example, the virtual modifier allows derived classes to override a method. The abstract modifier prevents a class from being instantiated directly and requires it to be inherited from.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Access Specifiers Example:

Here is source code of the C# Program to Illustrate the Use of Access Specifiers.

/*
 * C# Program to Illustrate the Use of Access Specifiers
 */
 
using System;
namespace accessspecifier
{
    class Program
    {
        static void Main(string[] args)
        {
            two B = new two();
            B.show();
        }
    }
    class one
    {
        private int x;
        protected int y;
        internal int z;
        public int a;
        protected internal int b;
    }
    class two : one
    {
        public void show()
        {
            Console.WriteLine("Values are : ");
            //x=10;
            y = 20;
            z = 30;
            a = 40;
            b = 50;
            // Console.WriteLine(+x); // Error x is not accessible
            Console.WriteLine(y);
            Console.WriteLine(z);
            Console.WriteLine(a);
            Console.WriteLine(b);
            Console.ReadLine();
        }
    }
}
Program Explanation

1. The program defines two classes, one and two, inside the accessspecifier namespace.
2. The one class has five member variables: x (private), y (protected), z (internal), a (public), and b (protected internal).
3. The two class inherits from the one class using the : syntax.
4. The show() method inside the two class displays the values of accessible variables (y, z, a, and b).
5. The x variable is commented out in the show() method as it is not accessible from the two class due to its private access specifier.

Program Output:
 
Values are :
20
30
40
50
Best Practices for Using Access Specifiers

Here are some best practices for using access specifiers:

advertisement
  • Use the `private` access specifier for fields and methods that should only be accessed by the class in which they are defined.
  • Use the `public` access specifier for fields and methods that need to be accessed by other classes.
  • Use the `protected` access specifier for fields and methods that need to be accessed by derived classes.
  • Use the `internal` access specifier for fields and methods that need to be accessed by other classes in the same assembly.
  • Use the `protected internal` access specifier for fields and methods that need to be accessed by derived classes in the same assembly and other assemblies.

Tips for using access specifiers

  • Always use access specifiers for class members.
  • Choose the right access specifier for each member.
  • Use access specifiers consistently throughout your code.
  • Don’t overuse access specifiers. Use them only when necessary.
Common Mistakes to Avoid When Using Access Specifiers

Here are some common mistakes to avoid when using access specifiers:

  • Not using access specifiers at all – This can lead to security vulnerabilities and make your code more difficult to maintain.
  • Using the wrong access specifier – For example, using public access for a member that should be private. This can expose sensitive data to other classes and make your code more difficult to debug.
  • Not using access specifiers consistently – This can make your code more difficult to read and understand.
  • Overusing access specifiers – This can make your code more complex and difficult to maintain.

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

advertisement
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.