Class Definitions in C#
C# uses the class keyword to define classes:
class Program { // Member Functions }
This code defines a class called Program . Once you have defined a class, you are free to instantiate it anywhere else in your project that has access to the definition. By default, classes are declared as internal , meaning that only code in the current project will have access to them. You can specify this explicitly using the internal access modifier keyword as follows:
internal class Program { // Class members. }
Alternatively, you can specify that the class is public and should also be accessible to code in other projects. To do so, you use the public keyword:
public class Program { // Class members. }
You can also specify that the class is either abstract (cannot be instantiated, only inherited, and can have abstract members) or sealed (cannot be inherited). To do this, you use one of the two mutually exclusive keywords, abstract or sealed . An abstract class is declared as follows:
public abstract class Program { // Class members, may be abstract. }
Here, Program is a public abstract class, while internal abstract classes are also possible.
The following table shows the allowed access modifier combinations for class definitions :
Modifier | Meaning |
---|---|
none or internal | Class accessible only from within the current project . |
public | Class accessible from anywhere . |
abstract or internal abstract | Class accessible only from within the current project, and cannot be instantiated, only derived from . |
public abstract | Class accessible from anywhere, and cannot be instantiated, only derived from . |
sealed or internal sealed | Class accessible only from within the current project, and cannot be derived from, only instantiated . |
public sealed | Class accessible from anywhere, and cannot be derived from, only instantiated . |