It's all static: Static classes and members in C#

Declare static classes and static members of a class to improve performance

Static classes and static members

Static classes and static members

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. To declare a class as static, you should mark it with the static keyword in the class declaration. The static keyword when used on a class declaration enforces that the class cannot be instantiated or inherited and that all the members of the class are static in nature.

There's no behavior in a static and 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 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 demonstrates how 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

        }

    }

Static method

Static methods are those that doesn'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 members. You can have static methods both inside a static or a non-static class. Also, you can have a static constructor in either a static class or a non-static class. A static constructor in a class 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 assessed.

Why should we use static methods anyway? 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 nonvirtual call sites due to which the extra check for whether the instance is null is eliminated. This might give you some performance benefits especially when you are writing performance critical code in your application.

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

The following code snippet illustrates how 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();

            }

        }

Static members

The CLR divides the memory into three distinct regions: the stack, the heap, and the high frequency heap. Static objects need to survive a GC collection and are stored in the high frequency heap. Static and constants objects are stored in the loader heap as they exist in the memory throughout the lifetime of the application; they don't need to be garbage collected. To be more precise, static objects are stored in the high frequency heap -- you typically have one such heap for each application domain.

Let's now take a look at static members of a class. A static object is one that persists in the memory till the time the application is in execution. The following code listing illustrates how the modified version of the FileLogger class 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.

This article is published as part of the IDG Contributor Network. Want to Join?

From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.