In C# programming, access modifiers are essential keywords that determine the visibility, scope, and accessibility of various program elements like classes, methods, variables, and properties. This concept plays a vital role in object-oriented programming, facilitating the enforcement of encapsulation and data concealment principles. Access modifiers are valuable in restricting unauthorized or unintentional access to internal data and implementation details, thereby enhancing the security and integrity of the program.
Type of Access Specifier
In C#, there are primarily six categories of access modifiers. These include:
The given code snippet defines a CSS class for a placeholder diagram. This class sets the background to a linear gradient with specific colors, adds rounded corners, padding, margin, and centers the content. Additionally, it specifies styles for the placeholder icon and text within the diagram.
Here, we will examine these access modifiers individually.
1) C# Public Access Modifier
In C#, the public access modifier provides greater flexibility. When a class member is defined as public, it is accessible from anywhere within the same assembly or even outside it. Public class members are frequently used to define the class interface and can be accessed through objects of derived classes. Unlike other access modifiers, the public modifier imposes no access restrictions.
Syntax:
It has the following syntax.
public class ClassName
{
public dataType variableName;
public void MethodName()
{
// block of code
}
}
In this syntax,
- ClassName: It declares the public class, which means that it is accessible from anywhere in the program.
- variableName: It declares a public member variable of a specified datatype, which means that it can be accessed from any other class or assembly.
- MethodName: It declares a public method named MethodName that can be called from anywhere. The method contains the logic or behavior for the class.
C# Public Access Modifier Example:
Let's consider an example to demonstrate the public access modifiers in C#.
Example
using System;
namespace AccessSpecifiers
{
class PublicTest
{
public string name = "John";
public void Msg(string msg)
{
Console.WriteLine("Hello " + msg);
}
}
class C# Tutorial
{
static void Main(string[] args)
{
PublicTest publicTest = new PublicTest();
// Accessing public variable
Console.WriteLine("Hello " + publicTest.name);
// Accessing public function
publicTest.Msg("Peter Decosta");
}
}
}
Output:
Hello John
Hello Peter Decosta
Explanation:
In this illustration, we've chosen a public class named "PublicTest" that includes a public variable and a public function. This designates both elements as public to enable access from external sources. Within the main method, an object of the PublicTest class is instantiated and both the variable and function are utilized. Ultimately, the function named Msg is invoked to display the result by employing the Console.WriteLine function.
2) C# Protected Access Modifier
In C#, the protected class elements are accessible within the class itself and its subclasses, even if they belong to a separate assembly. However, access to protected members is limited outside of derived classes. This ensures that functions or objects external to the class cannot interact with its protected members. Typically, protected class elements are used to define the internal workings of a class that should only be accessible to its subclasses.
Syntax:
It has the following syntax:
class BaseClass
{
protected dataType variableName;
protected void MethodName()
{
// block of code
}
}
In this syntax,
- BaseClass: A class that other classes can use to get their features.
- protected datatype variableName: It represents the protected variable, which can be accessed inside the same class and its subclasses.
- protected void MethodName: It defines the protected method, which is accessible within its own class and any derived subclasses.
C# Protected Access Modifier Example
Let's consider a scenario to demonstrate the restricted access modifiers in C#.
Example
using System;
class Creature
{
// using protected specifier
protected string message = "Creature Sound";
protected void MakeNoise()
{
Console.WriteLine("The creature makes noise: " + message);
}
}
class Cat : Creature
{
public void Meow()
{
// Accessing protected members of base class
message = "Meow!";
MakeNoise();
}
}
class C# Tutorial
{
static void Main()
{
Cat cat = new Cat();
cat.Meow();
}
}
Output:
The creature makes noise: Meow!
Explanation:
In this instance, we establish a Creature class that encompasses a protected function called MakeNoise, which is reachable in the subclass Cat. Within the Meow function of the Cat subclass, the content field is modified to Meow. Subsequently, we generate a cat class object and invoke its Meow function to display the result using the Console.WriteLine function.
3) C# Internal Access Modifier
In C#, the internal access modifier functions at the assembly level. When a member of a class is marked as internal, it is restricted to being accessed solely within the same assembly. External assemblies, even if referencing it, are unable to access it.
Syntax:
It has the following syntax.
internal class ClassName
{
internal dataType variableName;
internal void MethodName()
{
// block of code
}
}
In this syntax,
- internal: It defines the specifier that can be accessed only within the same project or assembly.
- ClassName: It represents the name of the class.
- VariableName: It defines the name of the variable.
- MethodName: It defines the name of the method.
C# Internal Access Modifier Example
Let's consider an example to demonstrate the internal access modifier in C#.
Example
using System;
namespace AccessSpecifiers
{
class InternalTest
{
internal string name = "Michael";
internal void Msg(string msg)
{
Console.WriteLine("Hello " + msg);
}
}
class Program
{
static void Main(string[] args)
{
InternalTest internalTest = new InternalTest();
// Accessing internal variable
Console.WriteLine("Hello " + internalTest.name);
// Accessing internal function
internalTest.Msg("Peter Decosta");
}
}
}
Output:
Hello Michael
Hello Peter Decosta
Explanation:
In this example, we create a class named InternalTest that contains an internal variable and an internal method. Inside the main method, we create an object of the InternalTest class. Since both are in the same assembly, the name variable and Msg method are accessible. Finally, we call the Msg method to print the output using Console.WriteLine method.
4) C# Private Access Modifier
In C#, the private Access Specifier is employed to define exclusive accessibility to the variable or function. It is the most restrictive form and is only accessible within the class where it is defined. It is not reachable from outside the class or by any derived classes.
Syntax:
It has the following syntax.
class ClassName
{
private dataType variableName;
private void MethodName()
{
// block of code
}
}
In this syntax,
- ClassName: It declares the name of the class.
- variableName: It represents the name of the private variable inside the class. It is only accessible inside the block where it is defined.
- MethodName: It represents the name of a private method. This method can only be called inside the class.
C# Private Access Modifier Example
Let's consider an example to demonstrate the private access modifiers in C#.
Example
using System;
class Calc
{
// Public method
public void start()
{
int result = add(100, 200); // Calling private method inside the same class
Console.WriteLine("The Result is " + result);
}
// Private method
private int add(int a, int b)
{
return a + b;
}
}
class C# Tutorial
{
static void Main()
{
Calc c = new Calc();
c.start();
}
}
Output:
The Result is 300
Explanation:
In this illustration, we define a class called Calculator with a pair of functions: the initialize function and the sum function. The initialize function invokes the sum function, which computes the addition of 100 and 200. The sum function is marked as private, preventing direct access from external sources outside the Calculator class.
Within the primary function, we generate a Calculator object, trigger the c.initialize function, and display the result through the Console.WriteLine method.
5) Protected Internal Modifier
Within C#, utilizing the protected internal access modifier allows a class member to be reached:
- Internally within the identical assembly by any class.
- By subclasses, regardless of whether they are in a separate assembly.
In simpler terms, this access modifier combines features of both protected and internal levels. It allows access within the same assembly and from any subclass, regardless of whether the subclass is in a separate assembly.
C# Protected Internal Modifier Example:
Let's consider a scenario to demonstrate the protected internal access modifier in C#.
Example
using System;
namespace C# Tutorial
{
public class Car
{
protected internal string m;
public Car(string m)
{
this.m = m;
}
}
public class SportCar : Car
{
public SportCar(string m) : base(m) { }
public void Display()
{
Console.WriteLine("SportCar m: " + m);
}
}
class Program
{
static void Main(string[] args)
{
SportCar myCar = new SportCar("Ferrari");
myCar.Display();
}
}
}
Output:
SportsCar m: Ferrari
Explanation:
In this illustration, a foundational class called Car is established, incorporating a string variable designated with a protected internal modifier. Subsequently, a subclass named SportCar is crafted to derive from Car, granting it access to the model field. Within the primary method, an instance of the SportCar class is instantiated, followed by invoking the Display method to showcase the output "SportsCar model: Ferrari".
6) Private Protected Access Modifier in C#
In C#, the private protected access modifier is the combination of private and protected access modifiers. It allows class members to be accessed within the same class or inside the derived classes in the same assembly. The private protected class members cannot be accessed from outside the assembly or by derived classes in a different assembly.
C# Private Protected Access Modifier Example
Let's consider a scenario to demonstrate the private protected access modifier in C#.
Example
using System;
namespace Point
{
public class C# Tutorial
{
private protected string msg = "Welcome to C# Programming tech";
private protected void Message()
{
Console.WriteLine(msg);
}
}
public class tech : C# Tutorial
{
public void Show()
{
Message();
}
}
class Program
{
static void Main(string[] args)
{
tech tc = new tech();
tc.Show();
}
}
}
Output:
Welcome to C# Programming tech
Explanation:
In this instance, we establish a class called C# Tutorial that includes a function named Message, designated with a private protected access modifier. Following this, we define a subclass that extends the C# Tutorial class. Within the entry point method, we instantiate the subclass and invoke the Show method to display the result utilizing the Console.WriteLine function.
Access modifier in C#
Here is a chart outlining the access specifiers in C#.
| Access Specifier | Same Class | Derived Class | Outside Class |
|---|---|---|---|
| Public Access Modifier | Yes | Yes | Yes |
| Private Access Modifier | Yes | No | No |
| Protected Access Modifier | Yes | No | No |
| Internal Access Modifier | Yes | Yes(if in the same assembly) | No |
| Protected Internal Modifier | Yes | Yes (If in same assembly or derived) | Yes (If in same assembly) |
| Private protected Modifier | Yes | Yes (Only if in the same assembly and derived) | No |
Important Points about Access Modifier in C#
Several important points of access modifiers in C# are as follows:
- Access modifiers are not allowed in a namespace because they do not enforce access control.
- The user can only use one access modifier at a time, except for private, protected, and protected internal.
- In C#, the internal modifier is the default access modifier in a class.
Conclusion
In summary, the C# access modifier plays a crucial role in the object-oriented programming language by defining the visibility and accessibility of various elements within a class or structure. These modifiers are essential for encapsulation, which safeguards data, promotes modularity, and enhances code maintainability. The C# access modifier includes options like public, private, internal, protected, protected internal, and private protected, all of which contribute to code security.
C# Access Modifiers FAQs
1) What are the Access Modifiers in C#?
In C#, access modifiers are keywords utilized to specify the visibility, scope, and accessibility level of classes, methods, variables, properties, and other elements within a program. This aspect plays a crucial role in the object-oriented programming (OOP) paradigm.
2) What are the main access specifiers in C#?
In C# programming, there exist primarily four access modifiers: public, private, protected, and internal.
The default access modifiers for a class in C# are private for class members and internal for the class itself.
The default access level for a modifier within a class in C# is referred to as the internal modifier.
4) Is it possible to assign multiple access modifiers to a class or method?
In C#, it is not possible to assign more than one access modifier to a single class, method, or member. Each class or method can only be associated with a single access modifier.
5) What is the internal access modifier in C#?
In C#, the internal access modifiers are at the assembly level. They allow access to class members within the same assembly.