C# static class

In C#, a static class is a class that cannot be instantiated and can only contain static members, such as static methods, static properties, and static fields. Static classes are commonly used to provide utility functions or global access points to shared resources.

Here’s an example of a static class in C#:

public static class MathUtils
{
    public static int Add(int a, int b)
    {
        return a + b;
    }

    public static int Multiply(int a, int b)
    {
        return a * b;
    }
}

In the example above, MathUtils is a static class that provides two static methods: Add and Multiply. Since the class is static, you don’t need to create an instance of MathUtils to use these methods. You can directly access them using the class name, like this:

int sum = MathUtils.Add(5, 3);
int product = MathUtils.Multiply(4, 2);

Static classes are often used for organizing utility functions or helper methods that don’t require maintaining state. They are also commonly used for creating extension methods, which allow you to add functionality to existing types.

It’s important to note that a static class cannot be inherited, and you cannot create instances of it. The compiler enforces these restrictions to ensure the static class remains stateless and cannot be modified.

Points to remember for C# static class:

When working with static classes in C#, there are several key points to remember:

  1. Static classes cannot be instantiated: Unlike regular classes, you cannot create instances (objects) of a static class using the new keyword. Static classes are meant to be accessed directly through their class name.
  2. Static members only: A static class can only contain static members, such as static methods, static properties, and static fields. These members belong to the class itself, rather than individual instances of the class.
  3. Static classes are sealed: By default, static classes are implicitly sealed, which means they cannot be inherited by other classes. This is because they are designed to provide utility functions or global access points and should not be extended or modified.
  4. Accessing static members: To access static members of a static class, you use the class name followed by the member name, without creating an instance of the class. For example: ClassName.StaticMember.
  5. Stateless behavior: Static classes are typically used for providing utility functions or helper methods that don’t require maintaining state. It’s generally recommended to keep static classes stateless, as they can be accessed concurrently from multiple threads.
  6. Global accessibility: Static members of a static class are globally accessible within the same assembly (or namespace, if the class is nested within a namespace). They can be accessed from anywhere in the codebase without needing to create an instance or pass references.
  7. Extension methods: Static classes are often used to define extension methods. Extension methods allow you to add functionality to existing types without modifying their source code. They are defined as static methods within a static class and require the first parameter to be preceded by the this keyword to indicate the type being extended.
  8. Naming conventions: It is common to name static classes with a name that reflects their purpose or functionality. It’s recommended to use PascalCase for naming static classes.

By keeping these points in mind, you can effectively utilize static classes in C# for creating utility functions, organizing code, and providing global access points to shared resources.

C# static class example:

Sure! Here’s an example of a C# static class that demonstrates some common use cases:

public static class StringUtils
{
    public static string ReverseString(string input)
    {
        char[] charArray = input.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }

    public static string TruncateString(string input, int maxLength)
    {
        if (input.Length > maxLength)
        {
            return input.Substring(0, maxLength) + "...";
        }
        return input;
    }

    public static bool IsPalindrome(string input)
    {
        string reversed = ReverseString(input);
        return input.Equals(reversed, StringComparison.OrdinalIgnoreCase);
    }
}

In this example, the StringUtils class is a static class that provides utility methods for string manipulation. Let’s go through each method:

  1. ReverseString takes a string as input and returns the reverse of the input string. It converts the string to a character array, reverses it using the Array.Reverse method, and then creates a new string from the reversed character array.
  2. TruncateString takes a string and a maximum length as input. If the length of the input string exceeds the maximum length, it truncates the string and appends an ellipsis (...) to indicate that it has been shortened.
  3. IsPalindrome checks if a given string is a palindrome, which means it reads the same forwards and backwards. It uses the ReverseString method to reverse the input string and then compares it with the original string using a case-insensitive comparison.

You can use these methods from the StringUtils static class without instantiating an object of the class. Here’s an example of how you can use these methods:

string reversed = StringUtils.ReverseString("Hello, World!");
Console.WriteLine(reversed);  // Output: "!dlroW ,olleH"

string truncated = StringUtils.TruncateString("This is a long sentence.", 10);
Console.WriteLine(truncated);  // Output: "This is a..."

bool isPalindrome = StringUtils.IsPalindrome("Racecar");
Console.WriteLine(isPalindrome);  // Output: True

In the example above, we call the static methods directly on the StringUtils class without creating an instance.