Author avatar

Dániel Szabó

Static vs. Instance Members

Dániel Szabó

  • Sep 16, 2019
  • 8 Min read
  • 36 Views
  • Sep 16, 2019
  • 8 Min read
  • 36 Views
Languages Frameworks and Tools
C#

Introduction

Object Oriented Programming (OOP) revolves around two main terms: one is objects and the other is instances. There are different theoretical ideas that are implemented by specific programming languages. In this guide, we will take a look at static and instance members, we will dissect the terms and see what they are all about, and explore how you can utilize them by adhering to some very simple rules. When we are working with classes we have two types of members, either static or instance members. The best approach to this, in my opinion, is to think of static members as members which belong to a class and instance members as members which belong to the object itself.

We can also distinguish three types of members.

  1. Static fields and properties
  2. Static methods
  3. Static classes

Let's start with the classes.

Static vs. Non-static Classes

Our classes are either static or non-static. When we have a non-static class it can contain static methods, properties, and even events. You can call these events even without instantiating the class.

The following code is a good example of that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace SvsI
{
    public class NonStaticDemo {
         public static string NoInstance() {
            return "I dont need no instantiation!";
        }
    }
    public class StaticVsInstance
    {
        static string AnotherNoInstance() {
            return "This does not need an instance either.";
        }
        static void Main(String[] args)
        {
            Console.WriteLine($"Says the NonStaticDemo class: {NonStaticDemo.NoInstance()}");
            Console.WriteLine($"Says the StaticVsInstance class: {StaticVsInstance.AnotherNoInstance()}");
            Console.Read();
        }
    }
}
csharp

The output produced by the code is the following.

1
2
Says the NonStaticDemo class: I dont need no instantiation!
Says the StaticVsInstance class: This does not need an instance either.
bash

Without using the public modifier, we cannot call the NoInstance method from the NonStaticDemo class as we do not inherit anything from that in our main class. Also note that we do not need the public keyword when we invoke the AnotherNoInstance method from within our main class as the accessibility level is correct this time.

In other words, when we talk about instance members, we talk about those members of a class that cannot be called or accessed without instantiating the class. Those that can be accessed are called static members.

Let’s look at a static class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace SvsI
{
    static class Frozen {
        public static int value = 99;
        public static string FrozenMethod() {
            return "Why would you do this?";
        }
    }
    public class StaticVsInstance
    {
        static void Main(String[] args)
        {
            Console.WriteLine($"The value of the Frozen class is {Frozen.value}");
            Console.WriteLine($"Says the Frozen class: {Frozen.FrozenMethod()}");
            Console.Read();
        }
    }
}
csharp
1
2
The value of the Frozen class is 99
Says the Frozen class: Why would you do this?
bash

For accessibility reasons, we are using the public keyword once again. This is to enable ourselves to access the method and property of the class itself. Developers create static classes if every method, property, or event that class implements are static. The use for this is that it prevents others from instantiating the class.

When we try to create a new instance from our Frozen class with this line,

1
Frozen a = new Frozen();
csharp

the compiler tells us that CS0712 Cannot create an instance of the static class 'Frozen'.

Static Methods

In short, when you define a static method, you allow access from that method only to static members of the class and you cannot access instance members.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace SvsI
{
    public class StaticMethod {
        public static int staticValue = 66;
        public int instanceValue = 88;
        public static string StaticallyMethoded() {
            return $"I can access the static value: {staticValue}";
        }
    }
    public class StaticVsInstance
    {
        static void Main(String[] args)
        {
            Console.WriteLine($"Says the StaticMethod class: {StaticMethod.StaticallyMethoded()}");
            Console.Read();
        }
    }
}
csharp

Calling the code gives us the following output.

1
Says the StaticMethod class: I can access the static value: 66
bash

The method has no problem accessing the static property, however, if we add the following code we will see a nice error message.

1
2
3
public static string InstanceValued() {
    return $"I cannot access the instance value: {instanceValue}";
}
csharp

CS0120 An object reference is required for the non-static field, method, or property 'StaticMethod.instanceValue' lets us know that instance properties cannot be accessed from static methods.

Static Properties and Fields

When we have a static field, we need to keep in mind that this field identifies only one storage location in memory. No matter how many instances we create, there will only be one copy of a static field. More often than not, as a result of their nature, static properties are used to store data which is meant to be shared by all instances of the class. A good example is if we want to keep track of the number of instances of a specific class.

Let's inspect it with the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
namespace SvsI
{
    public class Counter {
        public static int instances = 0;
        public Counter()
        { instances += 1; }
    }
    public class StaticVsInstance
    {
        static void Main(String[] args)
        {
            Counter c0 = new Counter();
            Console.WriteLine($"There are a total of {Counter.instances} instance(s) of the Counter class!");
            Counter c1 = new Counter();
            Console.WriteLine($"There are a total of {Counter.instances} instance(s) of the Counter class!");
            Counter c2 = new Counter();
            Console.WriteLine($"There are a total of {Counter.instances} instance(s) of the Counter class!");
            Counter c3 = new Counter();
            Console.WriteLine($"There are a total of {Counter.instances} instance(s) of the Counter class!");
            Counter c4 = new Counter();
            Console.WriteLine($"There are a total of {Counter.instances} instance(s) of the Counter class!");
            Counter c5 = new Counter();
            Console.WriteLine($"There are a total of {Counter.instances} instance(s) of the Counter class!");
            Console.Read();
        }
    }
}
csharp

The output is as follows.

1
2
3
4
5
6
There are a total of 1 instance(s) of the Counter class!
There are a total of 2 instance(s) of the Counter class!
There are a total of 3 instance(s) of the Counter class!
There are a total of 4 instance(s) of the Counter class!
There are a total of 5 instance(s) of the Counter class!
There are a total of 6 instance(s) of the Counter class!
bash

All we did was define the instances static field for the Counter class and, in the constructor, we increment by one each time a new instance is created. Due to the nature of static properties, we cannot access it with an instance reference, so we need to reference it via the type which will be our Counter class.

Conclusion

This topic covered all you need to know about the instance and static members in C#. we have enlisted all the necessary differentiators between properties, methods, and classes regarding the static keyword. From now on you, with a little practice,should be able to fully utilize this facility of C# to create even more sophisticated applications by relying on this important feature of the language. I hope this has been informative for you, and you found what you were looking for.

0