Lesson 9 - Static class members in C# .NET

C# .NET OOP Static class members in C# .NET

In the previous lesson, Arena with a mage in C# .NET (inheritance and polymorphism), we put our knowledge of inheritance and polymorphism to the test. In today's tutorial, we're going to go over static class members in C# .NET. Until now, we only used data, states, being carried by an instance. Fields, which we've defined, belonged to an instance and were unique to each instance. OOP, however, allows us to declare fields and methods on a class itself. We call these members static, sometimes called class members, who are independent of an instance.

Beware of static membersWARNING! Today's lesson will show you that static members are approaches that actually violate the object-oriented principles. OOP includes them only for special cases and in general everything can be written without static members. We always have to think carefully before adding static members. Generally, I would recommend for you not to use static members ever, unless you're absolutely sure what you're doing. Like global variables, which C#, fortunately, doesn't have, static members are something that enable you to write bad code and violate good practices. Today, we'll rather go over static methods and classes in .NET. If used wisely, there will be less evil in the world.

Static (class) fields

We can declare various elements as static, let's start with fields. As I mentioned in the introduction, static elements belong to a class, not to an instance. So the data stored there can be read even if an instance of the class has not been declared. Basically, we could say that static fields are shared among all class instances, but even that wouldn't be accurate since they aren't actually related to instances. Let's create a new project, name it something like Static, and create a simple User class:

class User
{
        private string name;
        private string password;
        private bool loggedIn;

        public User(string name, string password)
        {
                this.name = name;
                this.password = password;
                loggedIn = false;
        }

        public bool LogIn(string enteredPassword)
        {
                if (enteredPassword == password)
                {
                        loggedIn = true;
                        return true;
                }
                else
                        return false; // wrong password
        }

}

The class is simple, it represents a user in a system. Each user instance has its own name, password, and carries information about whether the user is logged in. In order for the user to log-in, we call the LogIn() method which takes a password as a parameter. The method verifies whether it's the right password. If the person behind the keyboard is really that user, it logs him/her in. It returns true/false depending on whether the login was successful. In reality, the password would be also hashed, but we won't do any hashing this time around.

When a new user registers, the system tells him/her what the minimum length of their password must be. This number should be stored somewhere. During user registration, we still wouldn't have its instance. The object has not been created and would only be created after the form has been completely filled and submitted. Therefore, we can't use a public minimalPasswor­dLength field in the User class for this purpose. Either way, we still need a minimum password length stored in the User class somewhere since it, naturally, belongs there. We'll make this value a static field using the static modifier:

class User
{
        private string name;
        private string password;
        private bool loggedIn;

        public static int minimalPasswordLength = 6;

        ...

}

Now, let's switch to Program.cs and print the field to the console. We can access this field directly in the class:

Console.WriteLine(User.minimalPasswordLength);

We can see the field really belongs to the class. We can access it from different places in the code without having to create a user. Alternatively, on the user instance, we wouldn't be able to access it:

User u = new User("Thomas White", "passwordissword");
Console.WriteLine(u.minimalPasswordLength); // this line causes an error

Visual Studio will report an error and the code won't be compiled.

Another practical use of static fields is to assign unique identification numbers to each user. If we didn't know what static members were, we'd have to check every user creation and increment a counter. Instead, we'll create a private static field nextId right on the User class. The next user who registers will have their id stored there. The first user's id will be 1, the second 2, and so on. The User will get a new attribute - id, that will be set in the constructor depending on what the nextId value is:

class User
{

        private string name;
        private string password;
        private bool loggedIn;
        private int id;
        public static int minimalPasswordLength = 6;
        private static int nextId = 1;

        public User(string name, string password)
        {
                this.name = name;
                this.password = password;
                loggedIn = false;
                id = nextId;
                nextId++;
        }

        ...

}

The class stores the next instance id by itself. We will assign this id to a new instance in the constructor and increase it by 1, which prepares it for the next instance. Not only fields can be static, this approach could be applied to a variety of datatypes.

Static methods

Static methods are called on the class. All they usually are is utilities that we need to use often and creating an instance every time would be counterproductive. C# implicitly uses static members. Have you noticed how we never have to create a console instance in order to write something to it? The WriteLine() method on the Console class is static. We're only allowed to run one console at a time, so it would be pointless to create an instance every time we wanted to use it. We've already experienced a similar situation with the Round() method in the Math class. It would be pointless to instantiate a Math class to do such a simple thing as rounding. Static methods are generally just there to help us where the instantiation is counterproductive or makes no sense at all.

Let's make another example, just to clarify. During user registration, we need to know the minimum password length before we create its instance. Also, it would be great if we could check the password before the program creates the user. A full check, in this case, would include checking whether the length is correct, making sure it doesn't contain accent characters, verifying that there is at least one number in it, and so on. To do this, we'll create a static ValidatePasswor­d() method:

public static bool ValidatePassword(string password)
{
        if (password.Length >= minimalPasswordLength)
        {
                // password validation code (omitted for simplification purposes)
                return true;
        }
        return false;
}

We'll call this method on the User class:

Console.WriteLine(User.ValidatePassword("passwordissword"));

Viewer beware! The ValidatePassword() method belongs to the class. Meaning that we can't access any instance fields in it. Those fields don't exist in the class context, rather in the context of an instance. It wouldn't make any sense to have the user's name in our method! You can try it out if you'd like to get a visual confirmation of its impossibility.

Password validation can be achieved without knowledge of static members. We could create a UserValidator class and write methods in it accordingly. Then, we'd have to create its instance to be able to call those methods. It'd be a bit confusing because the "concept of a user" would be unnecessarily split up into two classes. Now, thanks to static members, all of the information is neatly organized in one place.

Thinking back, we really don't want the minimalPasswor­dLength static attribute to be accessible from outside the class. What we'll do is make it private and create a static get method for reading. We know this approach well from previous lessons. Let's add the get method that retries both the minimum password length and the instance's id:

public static int GetMinimalPasswordLength()
{
        return minimalPasswordLength;
}

public int GetId()
{
        return id;
}

Program.cs should look something like this now:

User u = new User("Thomas White", "passwordissword");
Console.WriteLine("First user's ID: {0}", u.GetId());
User v = new User("Oli Pickle", "csfd1fg");
Console.WriteLine("Second user's ID: {0}", v.GetId());
Console.WriteLine("Minimum password length: {0}", User.GetMinimalPasswordLength());
Console.WriteLine("Password validation \"password\": {0}", User.ValidatePassword("password"));
Console.ReadKey();

Output screenshot:

Console application
First user's ID: 1
Second user's ID: 2
Minimum password length: 6
Password validation "password": True

Note that even the Main() method is static since we are only allowed to run one program at a time. Meaning that we're only able to call static methods from the Program class from within the Main() method. Now you know how to add such methods directly to Program.cs, but it doesn't make much sense to use this approach since the application logic should take place in encapsulated objects.

Static constructor

The class could also have a static constructor. A static constructor is called when the application starts and the class is being registered for use. It can be used for initialization, calculations and so on. Similarly to instance constructors, we are able to create instances of classes and store them into static fields in static constructors.

Static classes

If a class contains only utility methods or it doesn't make sense to create an instance from it, for example we will never run two consoles at a time, we can declare it as static. Keep in mind, we can't instantiate a static class (create instances) and cannot be inherited in C#. Most likely to prevent the creation of wild structures. Two static classes that we're already familiar with are Console and Math. Let's attempt to create an instance of the Math class:

Math m = new Math(); // this code causes error

VS will report an error. Static classes have all their members set to static, so it wouldn't make any sense to create an instance of it because the result would be an empty object.

Static registry

Let's create a simple static class. We could create a class containing only utility methods and fields, e.g. Math. However, I've decided I'll have us create a static registry. Which is basically how you share important data between classes without making an instance.

Let's say we're making a more robust application, e.g. a digital journal. The application would be multilingual, its features would include adding bookmarks, choosing folders for storing files, color schemes and even running at system startup. It would have adjustable settings, e.g. picking the first day of the week (Sunday/Monday), which would be accessed from various parts in the code. Without knowledge of static members, we'd have to pass the settings instance to all objects (calendar, tasks, notes...) through the constructor.

One workaround would be to use a static class to store these settings. It would be accessible everywhere in the program, without even having to create an instance. It would contain all the necessary settings that would be used by objects. Our static class would end up looking something like this:

static class Settings
{
        private static string language = "ENG";
        private static string colorScheme = "red";
        private static bool runAtStartUp = true;

        public static string Language()
        {
                return language;
        }

        public static string ColorScheme()
        {
                return colorScheme;
        }

        public static bool RunAtStartUp()
        {
                return runAtStartUp;
        }

}

All fields and methods must be declared with the static modifier as well as the class itself. I purposely didn't use the public class fields, and made get methods instead, so the values wouldn't be able to be changed. Which is still a bit uncomfortable from a programmer's point of view. Next time we'll learn how to go about doing this in a more efficient way.

Now we'll put our class to use even though we don't have a full journal application. Let's make a Calendar class and verify that we can truly access the Settings there. We'll add a method to it that returns all of the settings:

class Calendar
{

        public string GetSettings()
        {
                string s = "";
                s += String.Format("Language: {0}\n", Settings.Language());
                s += String.Format("Color scheme: {0}\n", Settings.ColorScheme());
                s += String.Format("Run at start-up: {0}\n", Settings.RunAtStartUp());
                return s;
        }

}

Last of all, print it all to the console:

Calendar calendar = new Calendar();
Console.WriteLine(calendar.GetSettings());
Console.ReadKey();

Console application
Language: ENG
Color scheme: red
Run at start-up: True

We see that calendar instance has no problem accessing all program settings.

Again, be careful, this code can be improperly used to share unencapsulated data. We must only use it in specific situations. Most data exchanges should happen using parameterized instance constructors, not through static members.

Static members appear very often in design patterns, we've mentioned them in the last lesson as well. We'll get in further detail in the approaches that bring object-oriented programming to perfection later on. For now, this will do. I don't want to overwhelm you :) In the next lesson, Properties in C# .NET, we'll look at what properties are in C# .NET.


 

Download

Downloaded 16x (77.19 kB)
Application includes source codes in language C#

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
1 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (13)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!