SoFunction
Updated on 2025-03-07

Analysis of the usage of access modifiers for C# class

This article analyzes the usage of access modifiers in C# in detail and shares it with you for your reference. The specific usage analysis is as follows:

By default, the class is declared internally, i.e. only the code in the current project can access it. It can be explicitly specified with the internal access modifier keyword, but this is not necessary, and the class defaults to a class of this type when defined. However, the default access level of C# method is: private.

The access level of the modifier of the method or attribute is shown in the figure below: 

Access modifier

meaning righteous

public

Access is not restricted and can be accessed within and outside of the class.

protected

Accessible domains are limited to or within classes derived from the class

internal

Accessible domains are limited to the assembly where the class resides

protected internal

protected or internal can access the domain that is limited to the program where the class resides or those derived from the class to which it belongs

private

Accessible domain is limited to the class to which it belongs


Combination of access modifiers that can be used in class definitions

The none or internal class can only be accessed in the current project
The public class can be accessed anywhere
abstract or internal abstract class can only be accessed in the current project, cannot be instantiated, can only be inherited
The public abstract class can be accessed anywhere, cannot be instantiated, can only be inherited
sealed or internal sealed class can only be accessed in the current project, cannot be derived, can only be instantiated
The public sealed class can be accessed anywhere, cannot be derived, can only be instantiated

The following is a description of the default access modifiers for methods, classes, etc. in C#

Interface

The interface member access modifier defaults to public, and the access modifier cannot be displayed.

Class

The constructor defaults to the public access modifier.

The destructor cannot display the use of access modifiers and defaults to the private access modifier.

The default access modifier for the class member is private;

Enum (enum)

Enumeration type members default to public access modifiers, and use modifiers cannot be displayed.

Structure

Structure members default to private modifiers.

Structure members cannot be declared as protected members because structures do not support inheritance.

Nested Types

The default access modifier for nested types is private. The default access type of the class and structure is the same as the default access type

I hope this article will be helpful to everyone's C# programming.