Programming in C#, Part 6: Static & Extension Methods

Welcome to our next tutorial about the static keyword, which has nothing to do with electricity. This keyword has a lot of good uses in the right circumstances, and we’ll learn about what it is and how to use it. As per usual, anything in bold represents a topic I won’t be going over right now, and it would be good outside research for you to look in.

What is the static keyword?

So we can mark a few things as static, classes, functions, and variables. This is just another type of keyword we can apply, so we have have public static int or private static int, we can have public static readonly int, etc.

When we mark a function or variable as static, we’re saying that this function is under the class but not part of any instances made of that class. It’s like making a global variable of that type.

Normally when we make a variable or function, we access it from an instance of the class; we make a new variable of that class and we can access all of that instances variables. If we change a variable in one instance, only that instance’s variables are changed.

With the static keyword, it is no longer part of an instance. If you make a public static variable, you won’t be able to get that variable from the instance you make of that class, because it doesn’t exist as part of the instance. It exists as part of the class type. When we get rid of our variable, the static variable’s values aren’t reset, they stay throughout the lifetime of the program.

Let’s take a look at a basic example of this concept.

class Example
{
    public string name = "";
    static int count = 0;
    public static int GetCount() { return count; }
    public Example(string name)
    {
        this.name = name;
        count++;
    }
}

//In our main program
static void Main()
{
    Example one = new Example("Bob");
    Example two = new Example("Jim");
    Example three = new Example("Sally");
    Console.WriteLine("We have: " + 
                      one.name + ", " +
                      two.name + ", " +
                      three.name);
    Console.WriteLine("This is " + Example.GetCount() + " people!");

    Console.ReadLine(); //Wait so the program doesn't end instantly.
}

So here we have a basic example of tracking how many times we’ve made a new instance of our class Example. We make three instances, we list out their names manually, then we use Example.GetCount() to find out how many we have. You can pop this into a console app and see the result; it should give you 3. Notice we didn’t use one.GetCount(), in fact that function doesn’t exist if you tried to use it that way. Because the instance doesn’t have that function, the class does.

Static Functions

One thing to note about static functions is that they can only touch local variables and other static variables. Notice how we returned count (which was a static variable) in our function GetCount()? If we tried to access the name string, it wouldn’t let us, because that’s instance specific. How would it know which name to use? Those belong to the instances, not to the class.

You can do lots with static functions, in fact you’ve probably already been using them a lot! We just used them a second ago. Both Console.WriteLine() and Console.ReadLine() are static. Notice how Console is a class, and you’ve never had to make an instance of it. We’ve never had to define Console console = new Console(), it’s been a static function all this time, and you never even knew.

Static Classes

There’s not much special about static classes, they essentially just require everything inside of them to be static. If you try to make a non-static variable or method, you’ll get an error. You also won’t be able to make an instance of them at all. You do need a static class to make extension methods however, which we’re about to get into.

Extension Methods

Extension methods are super useful, and something I learned about way too late into my learning process. They essentially let you extend other existing types. So you can add your own functions onto pre-existing types. So you could add a useful method that doubles an int, and you would just use myInt.Double() and it would double it’s value that easily. Let’s take a look at the format for this.

public static class IntExtensions
{
   public static int Double(this int myInt)
   {
        return myInt * 2;
   }
}

 

So here we have a static class, and a static function, both of which are needed for an extension method. For our return type, we specify int because we want to return the int value, but doubled. Our parameter is an int, for the type we’re extending, and you’ll notice that we have a this in front. This is what defines our function as being an extension method, whatever has a this in front of the type is what we’re extending. Without that it won’t work properly.

You can do this sort of thing for most types, you can make a library of useful tools using extension methods!

Extra Practice

Using static variables can be pretty situational, so in this case I’d honestly just say experiment with it. Try some new things, make some static variables and functions and see what you can do. Make some cool extension methods you can save and use later.

Next Time

We’re jumping into the world of delegates and lambdas.

Support

Are you having trouble with understanding this tutorial? Please feel free to contact me via email at KoseckCory@gmail.com or message me on discord at 7ark#8194.

I would love to get feedback from people so I can add and improve these tutorials overtime. Letting me know what you’re confused about will let me update the tutorials to be more concise and helpful.

If you’re interested in supporting me personally, you can follow me on Twitter or Instagram. If you want to support me financially, I have a Patreon and a Ko-fi.

2 comments on “Programming in C#, Part 6: Static & Extension MethodsAdd yours →

Leave a Reply

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