Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Edit] C# Classes: Static Definition #5460 #5462

Merged
merged 12 commits into from
Nov 21, 2024
46 changes: 45 additions & 1 deletion content/c-sharp/concepts/classes/classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,51 @@ public class BankAccount {

## Static Classes

Static classes are defined using the `static` keyword and exclusively contain static members, such as methods, properties, and fields. Unlike regular classes, static classes cannot be instantiated with the `new` keyword. Instead, their members are accessed using the class name itself. These classes are commonly used for utility functions or to group related functionality.
Static classes are defined using the `static` keyword and exclusively contain static members, such as methods, properties, and fields. Unlike regular classes, static classes cannot be instantiated with the `new` keyword. Instead, their members are accessed using the class name itself. These classes are commonly used for utility functions or to group related functionalities.

The `static` keyword forces all fields, methods, and properties to require this keyword. This means that if a user tries to create any of these without the `static` keyword, the code will not run and will produce a compile-time error. The reason behind this is that the user can not create an instance of a static class without using this keyword. Any methods, properties and fields that are not marked as `static` would be unreachable.

### Example

In the example below, a static class called `MyStaticClass` is created. The commented out code shows what a user can not do with static classes. If these commented out pieces of code were to be uncommented, the code would not compile. The example also shows how properties and methods in the `MyStaticClass` class are created and used in the `CallingClass` class:

```cs
using System;

public class CallingClass
{
public static void Main()
{
Console.WriteLine(MyStaticClass.StaticField);

// The following will produce a compile-time error
// MyStaticClass NonStaticError = new MyStaticClass();

int DoubleFive = MyStaticClass.GetDouble(5);
Console.WriteLine(DoubleFive);
}
}

public static class MyStaticClass
{
// The following will produce a compile-time error
// public int NonStaticField = 5;

public static int StaticField = 20;

// Returns double of the value given
public static int GetDouble(int value) {
return value * 2;
}
}
```

The above code produces the following output:

```shell
20
10
```

## Partial classes

Expand Down
Loading