Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Modify Classes with Style

Aug 6, 2019 • 6 Minute Read

Introduction

Access modifiers provide a way to control access to a class and its members. They are also used to control access to specific types. With this level of control comes a built-in safety that improves the robustness of the application. It prevents accidental creation of bugs in the code. This will be a thorough guide for you to understand the reasons behind the concept.

Access Modifiers

There are basically six accessibility levels:

  1. Public
  2. Protected
  3. Internal
  4. Private
  5. Protected internal
  6. Private protected

Only one access modifier is allowed for a member or type, unless you are using protected internal or private protected.

You cannot assign access modifiers to namespaces, as these do not possess access restrictions. Top-level types can only have internal or publicaccessibility, the default for these types is internal, if not specified otherwise.

The access modifiers provide one of the three pillars of object-oriented programming. This pillar is called Encapsulation. The other two pillars are Inheritance and Polymorphism.

Encapsulation is about information hiding or, more correctly, providing appropriate access to specific information for those who are authorized.

As a best practice, developers usually define fields with private access level and provide getter and setter methods as public. This way, only controlled modification can happen to the fields.

Here is an example of that:

      public class Developer
    {
        private string Name;
        private int Salary;

        public Developer(string name, int salary)
        {
            this.Name = name;
            this.Salary = salary;
        }

        public void SetName(string name)
        {
            if (!String.IsNullOrEmpty(name))
            { this.Name = name; }
        }

        public string GetName()
        { return Name; }

        public void SetSalary(int amount)
        {
            if (amount.GetType() == typeof(int))
            { this.Salary = amount; }
        }

        public int GetSalary()
        { return Salary; }
    }
    

If we want to initialize our object, we should do the following.

      Developer Daniel = new Developer("Szabó Dániel Ernő",100000);
    

Now we are able to use the GetName to see the property.

      Console.WriteLine(Daniel.GetName());
    

Also, we could use the SetSalary to change the property.

      Daniel.SetSalary(2000000);
Console.WriteLine(Daniel.GetSalary());
    

Note that the following will throw an error.

      Daniel.Salary = 300000;
    

This is due to the fact that the property is private and the only way to modify it is with the call of the appropriate setter called SetSalary!

C# also differentiates other types of modifiers, that are not only bound to classes but different data types and structs.

  1. abstract
  2. async
  3. const
  4. static
  5. sealed...

For a full reference, you should visit this documentation as this guide is not going to demonstrate the full arsenal.

Internal

This access modifier ensures that the object can only be accessed inside its own assembly but not from other assemblies.

This means a class like this:

      public class InternalDemo
{
	internal int number = 99;
}
    

The above code allows access to the number property from the same program/assembly. Using it from another program is going to throw you an error saying "It cannot access the property."

Private

These properties can only be accessed inside the class, there is no way to access it from other classes or outside of the class.

      class Developer
{	
	private string Name = "Daniel";
}

class Program
{
	static void Main(string[] args)
	{
		Developer D = new Developer();
		Console.WriteLine(D.Name);
	}
}
    

The WriteLine function will throw the exception notifying us of the restriction posed by the access modifier.

Public

This access modifier makes the property/method accessible to the entire project we are working on. This is the loosest modifier and should be used with care.

      class Player
{	
	public string Game = "Rocket League";
}

class Program
{
	static void Main(string[] args)
	{
		Player R = new Player();
		Console.WriteLine(D.Game);
	}
}
    

Protected

This modifiers allows the method or property to be accessible from within the class and from every class that is derived from that class.

      class Developer
{
	protected string Name = "Daniel";
}

class GameDeveloper : Developer
{
	void Print()
	{
		Console.WriteLine(Name);
	}
}
    

The WriteLine function has no problem accessing the property as projected by the usage or the protected access modifier.

Protected Internal

This is a combination of protected and internal modifiers. This means we can only access the member from within the same assembly or in a derived class in other assemblies or projects.

Private Protected

This modifier is also a combined one. Part of its magic comes from the private and another part comes from the protected keywords. This allows us to access members inside the container class or in a class that derives from a container class, but this is restricted only to the given assembly/project.

Sealed

When you apply this to a class you prevent other classes from inheriting from it. This can also be applied to methods or properties that override a virtual method or property in the base class. This means other classes can derive from your class but cannot override the methods or properties.

Conclusion

All in all, access modifiers are at the very core of the C# programming language. Every bigger application takes these security restrictions into account and the feature allows the fine-tuning of accesses throughout the whole run time. Developers either love it or hate it; there is no middle ground. I remember when I started out learning C#, it gave me goosebumps to troubleshoot issues coming from these access modifiers. But over time, if you consciously keep this feature in mind, you get used to it. I hope this was worth your while.

Dániel Szabó

Dániel Szabó

Written content author.

More about this author