C# Keywords Tutorial Part 79: static

C# Keywords Tutorial Part 79: static

C# is a strong and adaptable programming language used to build many kinds of applications. The ability to define variables, functions, and classes as static is one of the capabilities offered by C#. The static keyword in C# will be discussed in this blog article, along with various use examples.

Static is what? When declaring variables, methods, and classes in C# that are related to a type rather than an instance of that type, the static keyword is used. This signifies that all instances of the type share a static variable, method, or class.

Examples Here are some examples of how static can be used:

Example 1: Static variable

public class MyClass
{
    public static int Count = 0;
    
    public MyClass()
    {
        Count++;
    }
}

MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
MyClass obj3 = new MyClass();

Console.WriteLine(MyClass.Count); // Output: 3

In this example, we declare a static variable called Count in the MyClass class. We then create three instances of the MyClass class, which each increment the Count variable when they are created. Finally, we output the value of Count, which is 3 because we created three instances of the MyClass class.

Example 2: Static method

public class MyMath
{
    public static int Add(int x, int y)
    {
        return x + y;
    }
}

int result = MyMath.Add(3, 4);
Console.WriteLine(result); // Output: 7

In this example, we declare a static method called Add in the MyMath class. We then call the Add method and pass in two integers, which are added together and returned by the method. Finally, we output the result of the method, which is 7 because we passed in 3 and 4.

Example 3: Static class

public static class MyUtility
{
    public static void DoSomething()
    {
        // Code to do something
    }
}

MyUtility.DoSomething();

In this example, we declare a static class called MyUtility. We then declare a static method called DoSomething in the MyUtility class, which contains some code to do something. Finally, we call the DoSomething method, which executes the code in the method.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *