C# Access Modifiers / SpecifiersC# Access modifiers or specifiers are the keywords that are used to specify accessibility or scope of variables and functions in the C# application. C# provides five types of access specifiers.
We can choose any of these to protect our data. Public is not restricted and Private is most restricted. The following table describes about the accessibility of each.
Now, let's create examples to check accessibility of each access specifier. 1) C# Public Access SpecifierIt makes data accessible publicly. It does not restrict data to the declared block. ExampleOutput: Hello Shantosh Kumar Hello Peter Decosta 2) C# Protected Access SpecifierIt is accessible within the class and has limited scope. It is also accessible within sub class or child class, in case of inheritance. ExampleOutput: Compile time error 'ProtectedTest.name' is inaccessible due to its protection level. Example2 Here, we are accessing protected members within child class by inheritance. Output: Hello Shashikant Hello Swami Ayyer 3) C# Internal Access SpecifierThe internal keyword is used to specify the internal access specifier for the variables and functions. This specifier is accessible only within files in the same assembly. ExampleOutput: Hello Shantosh Kumar Hello Peter Decosta 4) C# Protected Internal Access SpecifierVariable or function declared protected internal can be accessed in the assembly in which it is declared. It can also be accessed within a derived class in another assembly. ExampleOutput: Hello Shantosh Kumar Hello Peter Decosta 5) C# Private Access SpecifierPrivate Access Specifier is used to specify private accessibility to the variable or function. It is most restrictive and accessible only within the body of class in which it is declared. ExampleOutput: Compile time error 'PrivateTest.name' is inaccessible due to its protection level. C# Private Specifier Example 2Output: Hello Shantosh Kumar Hello Peter Decosta Next TopicC# Encapsulation |