Programming Perplexions: Debunking the Keyword “static”

In programming your C#, Java, or any programming language that uses the keyword “static” may seem to look confusing at first. What do we really mean by it and why do we keep on using it especially on our main method? We keep on using it but yet some don’t know why and how it works. If your a beginner to programming, you’d probably head-banged yourself to learn why but can’t find a decent explanation. Tutorials and answers you’ve read on stackoverflow may still seem confusing and nor may your teacher is. So here I am to debunk your knowledge on what does it really do. Hopefully by the end of the article, you get enlightened. Here’s a simple program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StaticDemo
{
    class Program
    {
        public static void Main(string[] args)
        {
        }
    }
}

Note that this is a C# program. Pretty much same as Java and others.

Let’s define “static” as defined on Wikipedia:
In computer programming, a static variable is a variable that has been allocated statically—whose lifetime or “extent” extends across the entire run of the program.

 

Still confused? Sounds deep isn’t it? Let me translate it in Layman’s terms:

It is a variable that changes based on what you assigned. Its value is brought throughout the entire program and during the program is running. If the program stops, the value is back to its initializing value when it launches again.

 

Still confused? I tried my best (I think?). The thing is theory isn’t enough to understand this or rather, anything on programming is never about theory. So let me give examples rather. Let’s modify our basic program and show you some scenarios.

1.) Instantiating Functions and Initializing Variables

Let’s try it out with functions. Here’s a basic program on incrementing ’till 3:

class Program
{
    int number = 0;
    public static void Main(string[] args)
    {
        Program p = new Program(); //Program is the class name
        p.Function1(); //Calls Function1
        Console.ReadKey(); //Stops the program to see output. Press any key to continue
    }
    public void Function1()
    {
        while(number < 3)
        {
            number++; //increments the number
            Console.WriteLine(number); //displays the number
        }
    }
}

Note that this doesn’t use the keyword “static” yet.

It’s just basically incrementing “number” until its less than 3 based from the while-loop’s condition. If we run the program, it should look like this:

1

 

Now lets add “static” on our Function1(). It should now be:

public static void Function1()

You will see some errors indicating its from the “number” variable and p.Function1(). Let’s have a peek on the specific errors by hovering your cursor on them.

1.1) Static Functions

Well go through the first one from p.Function1(). Let me discuss as well in this portion on declaring static functions:

2

It says “<The function> cannot be accessed with an instance reference; qualify it with a type name instead“. How was your interpretation of the error message? Kinda complicating for beginners if you’d ask me but what the compiler is trying to say is that it cannot be instantiated as an object attribute. For short, it cannot be “dotted“. As in reading it in english terms, doing “pee-DOT-function one” ( read as p.Function1() ) is illegal wherein Function1() follows the DOT which was used to specify the object’s property. DOT-ing a static function is not allowed as it is a rule of being a static function.

Now what do I mean by object attribute? Properties, they call it. If you’ll notice the code, you have a Program object declared on and on p, you have an attribute which is Function1()… and that explanation pretty much tells it in technical terms.

The solution? remove p. and it should now be Function1(); Simple as that. Do I need to explain it again.

 

Now this leaves the question “Why is our Main Method always declared in static?”. For three reasons:

  1. You cannot declare it as a property in the object simply because it is the method where you run everything.
  2. It only has one purpose and its to call functions.
  3. The compiler is designed for it to be coded that way so you have no choice. You don’t want to confuse the compiler on which will be the first method will it call.

But logically speaking, you cannot do something like this:

Object o = new Object();
o.Main("arg1","arg2", <insert more args here>);

 

Because it doesn’t make any sense using your Main Method for several purposes as that.

 1.2) Static Variables

3

 The error says “An object reference is required for the non-static field, method, or property <variable>“. From the sentence itself, since number is not declared in static, its asking for an object reference. For short, it needs to be DOTTED. So if we declare Program as an object inside Function1 and made number as a property of the Program object, it will work. So the code should be like this:

public static void Function1()
 {
    Program p = new Program();
    while (p.number < 3)
    {
        p.number++;
        Console.WriteLine(p.number);
    }
}

We made a Program object through p variable and made number a property of Program.

Now there is a simpler solution rather than declaring a Program object and its to make number static. Reason is the error message is indicating that variables have to be in a non-static form. Lets do the opposite then, making the variable static. Its pretty easy plus I don’t have to edit each and every variable within the function. So your number variable should be declared like this:

static int number = 0;

and no need to declare a new Program object.

So to recap everything, your code should look like this:

class Program
{
    static int number = 0;
    public static void Main(string[] args)
    {
        Program p = new Program();
        Function1();
        Console.ReadKey();
    }
   public static void Function1()
    {
       while (number < 3)
       {
           number++;
           Console.WriteLine(number);
       } 
    }
}

Rather, I can just remove the Program object inside as it doesn’t serve any use anymore.

Run the program and it should be the same:

4

 

2.) The effect of “static” on values

Now that we’re done on functions, this is the most important part, how does “static” affect the values during processing of data. Now let’s modify a bit our program earlier and reuse the same class but we’ll only focus on the 2 variables on top, namely staticToday1 and today1 which is static and non-static. Here’s the entire program:

class Program
 {
    public static long staticToday1 = DateTime.Now.TimeOfDay.Ticks;
    public long today1 = DateTime.Now.TimeOfDay.Ticks;
    public static void Main(string[] args)
    {
        Program p = new Program();
        p.checkDifference();
        Console.ReadKey();
    }
    public void checkDifference()
    {
        Console.WriteLine("Current Data. Notice that the milisecond changes: ");
        TimeSpan withoutStatic1 = new TimeSpan(today1);
        TimeSpan withStatic1 = new TimeSpan(staticToday1);
        Console.WriteLine("Without Static 1: " + withoutStatic1);
        Console.WriteLine("with Static: " + withStatic1);
        Console.WriteLine("Press any key to exit");
    }
 }

I used Timestamp ticks to be very  specific. Before I explain the code, let me show you how the output looks like:

5

The program is pretty much the same as the first one but modified with the use of time stamps to get specific. If you will notice, the values are different considering they just have the same code base. Why is that? You’re correct, the static data is persisted meaning, since it was declared on the first lines of the program, its value then was taken into account rather than its value when it was displayed on the screen. Value initialized and value displayed are two different things.

Now to explain the code:

  • DateTime.Now.TimeOfDay.Ticks – Gets the current time and date through specific tick format. Its formatted as a long type (E.g. 414066525810). Certain range of digits represent the time and date.
  • TimeSpan variable = new TimeSpan(DateTime Ticks) – This object converts your ticks which you defined into a human readable time. Formatted as HH/MM/Secs.Milisecs (As seen on the screenshot).

Now you might say that it could be the speed of the processing. Well it is definitely the speed. Its just that static values doesn’t change based from when will it be outputted. Still confused? Let’s try another scenario. I’ll add 2 more variables. Pretty much adding a #2 of the same variable to prove further:

class Program
 {
    public static long staticToday1 = DateTime.Now.TimeOfDay.Ticks;
    public static long staticToday2 = DateTime.Now.TimeOfDay.Ticks;
    public long today1 = DateTime.Now.TimeOfDay.Ticks;
    public long today2 = DateTime.Now.TimeOfDay.Ticks;
    public static void Main(string[] args)
    {
        Program p = new Program();
        p.checkDifference();
        Console.ReadKey();
    }
    public void checkDifference()
    {
        Console.WriteLine("Current Data. Notice that the milisecond changes: ");
        TimeSpan withoutStatic1 = new TimeSpan(today1);
        TimeSpan withoutStatic2 = new TimeSpan(today2);
        TimeSpan withStatic1 = new TimeSpan(staticToday1);
        TimeSpan withStatic2 = new TimeSpan(staticToday2);
        Console.WriteLine("Without Static 1: " + withoutStatic1);
        Console.WriteLine("with Static: " + withStatic1);
        Console.WriteLine("Without Static 2: " + withoutStatic2);
        Console.WriteLine("with Static: " + withStatic2);
        Console.WriteLine("Press any key to exit");
    }
 }

If you’ll notice, I specifically added today2, staticToday2, withoutStatic2, and withStatic2. Now Let’s try to run the program and look at the values:

6

If you’ll notice, static values immediately got their values from when they were initialized compared to non-static values, their values are based from when they were displayed on the screen. Even the exact speed of processing, static was able to get it. The static data is taken synchronously and doesn’t re-initialize again(reset the values for short) whenever the function is called. Just imagine whenever you refresh the page, the data doesn’t get lost nor gets changed. The data remains the same as if it acts as a global variable, also the reason why its usually declared outside functions. Going back to static’s definition:

In computer programming, a static variable is a variable that has been allocated statically—whose lifetime or “extent” extends across the entire run of the program.

Rereading it again, are you getting the picture now? Hope you do. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *