Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the default access for a class in C#?
In C#, when no access modifier is specified for a class, the default access level is internal. An internal class can be accessed from any code within the same assembly but is not accessible from other assemblies.
This means that classes declared without an explicit access modifier are visible throughout the current project or assembly, but remain hidden from external assemblies that might reference your code.
Syntax
Following is the syntax for declaring a class with different access levels −
// Default access (internal)
class MyClass { }
// Explicitly internal
internal class MyClass { }
// Public access
public class MyClass { }
Class Access Modifiers
C# provides two access modifiers that can be applied to classes −
| Access Modifier | Description | Accessibility |
|---|---|---|
public |
No access restrictions | Accessible from any assembly |
internal (default) |
Access limited to current assembly | Accessible only within the same assembly |
Using Default (Internal) Access
Example
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
internal double length;
internal double width;
double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
}
}
}
The output of the above code is −
Length: 4.5 Width: 3.5 Area: 15.75
Comparing Internal vs Public Classes
Example
using System;
// Default access (internal) - same as 'internal class InternalClass'
class InternalClass {
public void ShowMessage() {
Console.WriteLine("This is an internal class");
}
}
// Public access - can be accessed from other assemblies
public class PublicClass {
public void ShowMessage() {
Console.WriteLine("This is a public class");
}
}
class Program {
static void Main(string[] args) {
InternalClass internal1 = new InternalClass();
internal1.ShowMessage();
PublicClass public1 = new PublicClass();
public1.ShowMessage();
}
}
The output of the above code is −
This is an internal class This is a public class
Conclusion
The default access modifier for classes in C# is internal, which limits access to the current assembly. This provides a good balance between encapsulation and accessibility within your project while preventing external assemblies from accessing internal implementation details.
