Introduction to Static Classes of C# (C Sharp)

Classes are generally meant to be instantiated. Each instance of a class will contain its own copy of members. But there are certain cases when the class should not be instantiated and the members of the class should directly belong to the class. This is achieved using static classes. This article focuses on how C# supports static classes. It is illustrated with better examples.




Definition for static class is straight forward. Static classes are those which cannot be instantiated. Other than this, there are certain other restrictions/guidelines when using static classes. They are mentioned below:

• Use static classes only when your requirement demands it
• Static classes can only have static members
• Static classes can have only static constructors and not instance constructors
• Constructor of static classes is not callable. It will be marked with access modifier private ensuring that the class cannot be instantiated using new operator
• Static classes cannot be declared as sealed or abstract
• Never try to override or declare instance members inside static class

Best example for static classes to illustrate its importance will be the Environment class which provides you information about the environment of the current user who is logged in. However for better understanding, consider the following scenario and see how you can implement it using static classes.

Scenario: You are developing an application for a company named “XYZ Co”. The application is only for this company and no other company information has to be recorded. You have to store the company information like company name, address.

How do you do it? It is obvious that you will store all these information in a class. But how will you supply information to the class? You are not recommended to create instances. Because there is only one company related to your application. Then how will you store information about that company? You have to use static class. Here is a sample code to illustrate this scenario:

static class COMPANY {
private static string NAME = “XYZ Co”;
private static string ADDRESS = “67, ST.Thomas Street, Majestic Circle”;
private static string CITY = “Bangalore”;
private static string STATE = “Karnataka”;
private static string COUNTRY = “India”;
private static int PINCODE = 650017;
private static int PHONE_NUMBER = 080653412;

public static string getName() { return NAME;}
public static string getAddress() { return ADDRESS;}
public static string getCity() { return CITY;}
public static string getState() { return STATE;}
public static string getCountry() { return COUNTRY;}
public static int getPincode() { return PINCODE;}
public static int getPhoneNo() { return PHONE_NUMBER;}
}

In this example, you have created a static class called COMPANY. It has attributes like NAME, ADDRESS, CITY and much more. These attributes are recorded as class members. Since static class holds only static members, these members are declared as static. Since COMPANY class is static, it cannot be instantiated. Hence its member variables have to be initialized before using. There are multiple ways of initializing members of a static class. They are:
• You can directly initialize them at the time of declaration
• You can initialize member variables inside a static method
• You can initialize them inside a static constructor

Note that when you don’t initialize member variables at the time of declaration, they will be assigned with the default values based on their data type. In this example you have initialized them, if not string variables will be initialized to null and integer variables will be assigned with 0. If you don’t initialize them at the time of declaration then you have to ensure that you initialize them before their values are retrieved.

Initializing member variables inside a static constructor is appropriate because static constructor will be automatically triggered before you are trying to access or reference the member variable. You can still use your own static method to initialize member variables. But ensure you call this method explicitly and set all values before retrieving the member variables.

In this example, you have initialized all the member variables at the time of declaration itself. In addition, you have defined some methods to retrieve those member variable values. Now the question that might arise in your mind is: How to call a static class? Here is an example to access methods of the above mentioned static class:

class sampleClass {
public static void Main() {
string strName = COMPANY.getName();
string strAddress = COMPANY.getAddress();
string strState = COMPANY.getState();
string strCity = COMPANY.getCity();
string strState = COMPANY.getState();
string strCountry = COMPANY.getCountry();
int pinCode = COMPANY.getPincode();
int phoneNo = COMPANY.getPhoneNo();
Console.WriteLine(“Company “+ strName + “is situated in “+ strAddress + “, ”
+ strCity + “, ”+strState+”, ”+ strCountry +” - ”+pinCode+”\\n
Contact Number:”+phoneNo);
}
}

Output of this code will be:

Company XYZ Co is situated in 67, ST.Thomas Street, Majestic Circle, Bangalore, Karnataka, India – 650017
Contact Number: 080653412

In this example, note that you did not create any instance of the static class COMPANY. If you try to create an instance then it will end up in compilation error. You access the static class members directly using the static class name followed by the dot operator. Since all data members of COMPANY class are marked as private, you can access them only using the static methods as shown above.

If you prefer not to use static class but enforce that your class should be restricted to have only one instance, then there is an alternative solution for you. The solution is to implement singleton design pattern. If you implement singleton design pattern then your class can be instantiated only once.

You are allowed to inherit the class. Implementing singleton design pattern instead of static classes will make your code look simpler, enhance reusability and you will also have control over the objects that are created. Singleton classes look like the other classes that you create and you can pass object of this class as parameters to other class methods. But you cannot do so in case of static classes. You can access static class directly in your class if your class has visibility on the static class.

SetApp - 100 Apps for everything you ever wanted to do on Mac

Add to My Yahoo!


FREE Subscription

Subscribe to our mailing list and receive new articles
through email. Keep yourself updated with latest
developments in the industry.

Name:
Email:

Note : We never rent, trade, or sell my email lists to
anyone. We assure that your privacy is respected
and protected.

Visit .NET Programming Tutorial Homepage

______________________________________________________

Recommended Resource

| How Do You Establish Polymorphism in C# (C Sharp) | How Do You Overload == Operator in C# (C Sharp) ? | How Do You Overload == Operator in C# (C Sharp) ? | How to Perform User Defined Conversions Between Structures (Struct) | Illustration of C# (C Sharp) Keywords (params, ref, out) Used to Declare | Introduction to Static Classes of C# (C Sharp) | Introduction to Static Members of C# ( C Sharp) | Overview of Structs in C# (C Sharp) | Using Constructors and Destructors in C# (C Sharp) |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2019 - All Rights Reserved.