Static classes and static class members in C# explained

Declare static classes and static members of a class to improve performance of your .Net applications

Static classes and static class members in C# explained
diane39/Getty Images

The static keyword in the C# programming language allows you to define static classes and static members.

A static class is similar to a class that is both abstract and sealed. The difference between a static class and a non-static class is that a static class cannot be instantiated or inherited and that all of the members of the class are static in nature. To declare a class as static, you should mark it with the static keyword in the class declaration. 

There is no behavior in a static class or member, so there isn’t any point in allowing a static class to be inherited either. A static class can only have static members — you cannot declare instance members (methods, variables, properties, etc.) in a static class. You can have a static constructor in a static class but you cannot have an instance constructor inside a static class.

When to use a static class in C#

When should you go for a static class? Typically you can implement helper or utility classes as static classes since they don’t need to be instantiated or inherited and generally contain a collection of some reusable methods and properties. The following code listing illustrates what a static class in C# looks like.

public static class FileLogger
    {
        public static void Log(string message)
        {
            //Method to log data in a text file
        }
    }

When to use static methods in C#

Static methods are methods that don’t need an instance of the class to be invoked— they can be called on the class itself. Note that static methods can only access static class members. You can have static methods inside a static class or a non-static class. Also, you can have a static constructor in a static class or a non-static class. A static constructor is used to initialize the static members of a class. The static constructor of a class is invoked the first time a static member of the class is accessed.

Why should we use static methods? They’re a bit faster in execution than non-static methods, i.e., instance methods. The reason is that the runtime passes the this pointer as an implicit parameter to the non-static or instance methods. Note that for a non-static method the compiler emits the callvirt instruction even if the method is non-virtual. If you make your methods static, the compiler emits non-virtual call sites, eliminating the extra check for whether the instance is null. This might give you some performance benefits.

Therefore, if the application you are building is a performance-critical one, it may be worthwhile to use static types and methods in your code. The performance gains may be appreciable if your code makes large number of calls to such types and members.

The following code snippet illustrates what a static method looks like.

public static void Log(string message)
        {
             string filePath = @"F:\IDGLog.txt";
            using (StreamWriter streamWriter = new StreamWriter(filePath, true))
            {
                streamWriter.WriteLine(message);
                streamWriter.Close();
            }
        }

How to use static members of a class in C#

The CLR divides system memory into three distinct regions: the stack, the heap, and the high frequency heap. Since static objects can be accessed directly without creating instances of the class, they must exist in the memory throughout the lifetime of the application; they don’t need to be garbage collected. Therefore, static objects are stored in the high frequency heap. You typically have one high frequency heap for each application domain.

Let’s now take a look at static members of a class. Again, a static object is one that persists in the memory the entire time the application is in execution. Extending the logging example above, the following code listing illustrates what a FileLogger class with static members would look like.

public static class FileLogger
    {
        private static readonly object lockObject = new object();
        public static string FilePath
        {
            get; set;
        }
        public static void Log(string message)
        {
            lock (lockObject)
            {
                if(!string.IsNullOrEmpty(FilePath))
                using (StreamWriter streamWriter = new StreamWriter(FilePath, true))
                {
                    streamWriter.WriteLine(message);
                    streamWriter.Close();
                }
            }
        }
    }

Note the usage of the static property named FilePath. To ensure thread safety, the lock keyword has been used. A check has been made inside the Log() method to verify that the value of the FilePath property is non-null and not empty.

Remember, when application speed is of the essence, it might pay to use static methods. You can use them in both static classes and non-static classes. 

Copyright © 2019 IDG Communications, Inc.