C# Programming: Understanding the Basics of Static Functions and Classes

C# Programming: Understanding the Basics of Static Functions and Classes

ยท

2 min read

The keyword static is widely used in C# and other programming languages to indicate that a member (field, method, property, etc.) belongs to the class rather than an instance of the class. In C#, a static member can be accessed directly on the class, without the need to create an object of the class. This makes them useful in certain situations where you don't need or want to create an object of the class, but still need to use the functionality provided by the member.

Static Functions

In the C# language, a static function is a method that belongs to a class rather than an instance of a class. This means that a static function does not have access to the non-static fields and methods of an instance, and can only access static fields and methods of the class. To define a static function in C#, you use the static keyword before the return type of the function.

Let's consider the following class that has a static variable x and a static function MyFunc In this code, the function can use the static variable x, however, it cannot use the variable y :

public class MyClass {
    public static int x = 0;
    public int y = 0;
    public static void MyFunc() {
        x++;
        Console.WriteLine("StaticMethod : " + x);
    }
}

Now we can call the function without having to instantiate the class:

MyClass.MyFunc();

Static Classes

In C#, a static class is a class that cannot be instantiated, all of the members of a static class must also be static, including fields, methods, properties, and events. This means that you cannot use the new keyword to create an object of a static class. Because static classes cannot be instantiated, they cannot have instance constructors or destructors.

For example, consider the following code snippet:

public static class MyClass {
    public static int x = 0;
    public static int b = 0;
    public static void MyFunc() {
        x++;
        Console.WriteLine("StaticMethod : " + x);
    }
}

In this example, MyStaticClass is a static class and MyStaticMethod is a static method of the class, which can be called directly on the class, like this:

MyClass.MyFunc();

Thank you for reading, and let's connect! ๐Ÿค

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Twitter
If you like this article! Don't miss the upcoming ones, follow me and subscribe to my newsletter to receive more!
See you soon :)

Did you find this article valuable?

Support Hamza EL Yousfi by becoming a sponsor. Any amount is appreciated!

ย