Access Specifiers

Access specifiers determine the accessibility of a class method or data members. We’ll take a look at the public and private access specifiers. The public access specifier is used when you want to access a method or data members outside the class or even outside the project. For example, consider the following code:

using System;
 
namespace AccessSpecifiersDemo
{
    public class Test
    {
        public int number;
    }
 
    public class Program
    {
        public static void Main()
        {
            Test x = new Test();
 
            x.number = 10;
        }
    }
}

Example 1 – public Access Specifier

We declared our test class as public. This will allow the Program class to create Test instances. We also declared one public data member inside the Test class. We tested if we can access that data member from outside the Test class by assigning a value to it inside the  Main() method of the Program class. If we are to omit the use of the public keyword, then we won’t be able to create a Test class and access its data member. That is similar to the private access specifier.

using System;
 
namespace AccessSpecifiersDemo2
{
    private class Test
    {
        public int number;
    }
 
    public class Program
    {
        public static void Main()
        {
            Test x = new Test();
 
            x.number = 10;
        }
    }
}

Example 2 – private Access Specifier

We used the private keyword for class Test. Compiling this will produce an error because Test now can’t be accessed anywhere inside the Program class or any other classes. Note that even though the data member of the Test class is public, it cannot be accessed because the class itself is private which makes everything inside it inaccessible.

Note that if you don’t specify any access specifier for a class, it will use internal access specifier which means that only the classes within the current project can access the class. Using         internal is equivalent to public but it can’t be accessed outside the project. The following code has the same in effect.

class Test
{
}
internal class Test
{
}

If we made our class public but its data member is private, then we can create an instance of that class outside of it but the privatedata member cannot be accessed. The private data member can only be accessed by methods within the Test class.

using System;
 
namespace AccessSpecifierDemo3
{
    public class Test
    {
        private int number;
    }
 
    public class Program
    {
        public static void Main()
        {
            Test x = new Test();
 
            x.number = 10; //Error, number is private
        }
    }
}

Example 3 – Accessing a private Field Produces Error

There are more access specifiers available in C# and they will be discussed in later chapters when you are finish learning about inheritance.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *