C# Static Class, Methods, Constructors and Fields with examples

C# Static Class

A static class is a class that cannot be instantiated and contains only static data members. It is essentially a collection of utility methods or helper methods that can be called directly by the class name itself, without the need to create an instance of the class.

CSharp-static-class
C# static class

What are the advantages and disadvantages of static class in C#?

One advantage of using a static class is that it can improve the performance of your application since you don’t need to create an instance of the class in order to access its methods. This can be particularly useful if the methods in the class are called frequently, or if the class contains large amounts of data that would take up a lot of memory if stored in an instance of the class.

However, there are also some disadvantages to using static classes. One disadvantage is that they can make your code more difficult to test since you cannot create instances of the class to test its methods. This can make it more difficult to write unit tests for your code and can make it more difficult to isolate and debug problems. Additionally, static classes can make your code more difficult to maintain, since any changes to the class will affect all users of the class, not just the instances that are modified.

Rules for Static Class in C#

Here are some rules to keep in mind when working with static classes in C#:

  • A static class in C# can only contain static members. This means that all fields, methods, and nested classes within the static class must also be static.
  • A static class cannot be instantiated. You cannot use the new keyword to create an instance of a static class.
  • A static class cannot have instance constructors. This means that you cannot define a constructor for a static class that accepts any arguments.
  • A static class cannot inherit from any other class or implement any interfaces. This is because a static class cannot have any instances, and therefore cannot have any implementation of inherited methods.
  • A static class remains in memory for the lifetime of the application domain in which your program is running.
  • C# static class is by default sealed and therefore can’t be inherited by the child classes.

A static class can be used to contain utility methods or data that is shared across all instances of a particular type. However, it is generally a good idea to use static classes sparingly and to consider other design patterns such as singletons or utility classes with dependency injection if a more flexible solution is needed.

C# Static Class Syntax:

In C#, we can create a static class by using the static keyword with the class, as shown below.

static class MyStaticClass
{
    //static data members
    //static methods
}

C# Static Class Example

The following is an example of defining a static class to access the static data members and member functions without creating an instance of the static class.

using System;
namespace StaticClassExample
{
    // Static class
    public static class Employee
    {
        // Static Variables
        public static string firstName;
        public static string lastName;

        public static string Address;
        public static int Id;
        // Static Method
        public static void ShowFullName()
        {
            Console.WriteLine($" FullName: {Employee.firstName} {Employee.lastName}");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Accessing the static fields
            Employee.firstName = "Shekh";
            Employee.lastName = "Ali";
            Employee.Address = "Delhi";
            Employee.Id = 52894;

            Console.WriteLine($" First Name: {Employee.firstName} , Last Name: {Employee.lastName}");

            // Calling the static method
            Employee.ShowFullName();
            Console.WriteLine($" Address: {Employee.Address}");
            Console.WriteLine($" Employee Id: {Employee.Id}");

            Console.ReadLine();
        }
    }
}

In the above example, the Employee class is a static class that has static fields and method. To access the members of the Employee class, you don’t need to create an instance of the class. Instead, you can access the members directly through the class name.

Output:

static class example output
Static class example

Static data member

A static data member is a class member that is shared across all instances of the class. In other words, there is only one copy of the static data member that is shared among all instances of the class.

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

public class Counter
{
    // Static data member
    public static int count = 0;

    // Non-static data member
    public int id;

    public Counter()
    {
        // Increment the static data member
        count++;

        // Assign a unique ID to the non-static data member
        id = count;
    }
}

In the above code example, the Counter class has a static data member called count and a non-static data member called id. The static data member count is used to keep track of the number of Counter objects that have been created.

To access the static data member count, you don’t need to create an instance of the Counter class. You can simply access it through the class name:

// Accessing the static data member
int count = Counter.count;

On the other hand, to access the non-static data member id, you need to create an instance of the Counter class.

// Creating an instance of the Counter class
Counter counter = new Counter();

// Accessing the non-static data member
int id = counter.id;

What is a static method?

A static method is a method that is associated with the class itself, rather than with a specific instance of the class. This means that you don’t need to create an instance of the class to call a static method. Instead, you can call the static method directly through the class name.

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

public static class MathUtils
{
    // Static method
    public static int Add(int num1, int num2)
    {
        return num1 + num2;
    }
}

In the above code example, the MathUtils class has a static method called Add that takes two integers as arguments and returns their sum.

To call the ‘Add’ method, you don’t need to create an instance of the ‘MathUtils’ class. Instead, you can call the method directly through the class name:

// Calling the static method directly through class name.
int sum = MathUtils.Add(10, 30);

Static methods are often used to provide utility functions or to perform operations that are independent of any specific instance of a class.

C# Static Constructors

A static constructor is a special type of constructor that is used to initialize a static class or a static member of a class. It is called automatically by the .NET runtime when the class is first accessed, and it is used to initialize static fields or to run the code that needs to be execute only once.

Here is an example of a static class with a static constructor: Static Constructor in C# with examples

Differences between static and non-static class in C#.

Here are the list of some differences between static and non-static classes in C#:

  • Instance creation: A non-static class can be instantiated using the new keyword, while a static class cannot be instantiated.
  • Member access: Members of a non-static class can be accessed through an instance of the class, while members of a static class are accessed directly through the class name.
  • Inheritance: A non-static class can be inherited by another class, while a static class cannot be inherited.
  • Virtual methods: Non-static classes can have virtual methods, which can be overridden in derived classes. Static classes cannot have virtual methods.
  • Constructors: Non-static classes can have constructors, which are called when an instance of the class is created. Static classes cannot have constructors.
  • Data members: Non-static classes can have both static and non-static data members, while static classes can only have static data members.

When to use a static class in C#?

A static class in C# is a class that cannot be instantiated and only contains static members. It is intended to contain methods and fields that are independent of any particular object. A static class is created by using the static keyword in the class declaration.

Here are some guidelines for when to use a static class:

  • When you need a utility class that provides methods that you want to call without creating an instance of the class.
  • When you want to prevent the creation of instances of the class.
  • When you want to represent a singleton design pattern, where you only want one instance of the class to be created.

Here are some examples of when you might use a static class:

  • A math library that provides methods for performing common math operations such as calculating the square root or the absolute value of a number.
  • A utility class that provides methods for formatting strings or converting data types.
  • A class that provides access to application-level resources, such as a database or a configuration file.

FAQ

Here are some frequently asked questions about C# static class and static data members in C#:

Q: Can we have non-static members in a static class?

No, a static class can only have static members.

Q: Can a non-static class have static data members?

Yes, a non-static class can have both static and non-static data members.

Q: How do I access a static data member in C#?

You can access a static data member by using the class name followed by the member name, like this: ClassName.MemberName.

Q: Can you override a static method in a derived class?

No, you cannot override a static method in a derived class because static methods are associated with the class itself, rather than with a specific instance of the class, so there is no way to override them.

Q: Why we should avoid static classes?

01. Lack of flexibility: Static classes cannot be inherited, so they cannot be extended or modified. This can make it more difficult to reuse code or customize the behavior of a class.
02. Difficulty in testing: It can be difficult to test static classes because they cannot be instantiated. This means that you cannot use dependency injection to mock or stub static methods for testing purposes.
03. Tight coupling: Static classes can create tight coupling between different parts of your codebase. This can make it more difficult to understand the relationships between different types and to maintain your code over time.

References: MSDN-Static class and static data members

Related articles:

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments