Another often overlooked topic is the usefulness of static methods. Simply put, a static method is a method you can call without having to first create an object from a class.
In a traditional class, to use a method you first have to create an instance of it. Let’s say our class looks like this:
public class StaticTest
{
public string CombineName(string first, string last)
{
return first + ” “ + last;
}
}
To use our simple class, we do something like this:
StaticTest st;
st = new StaticTest();
string fullName = st.CombineName(“Arcane”, “Code”);
Looking at the ComineName method, you see it’s pretty simple. It doesn’t use any of the classes internal variables, call other methods, or anything else special. Seems like a lot of overhead to use a simple method. Fortunately, .Net provides a way we can call this method without having to create an object from it’s class. As you may have guessed, it’s the static keyword. A quick change to our method declaration is all that’s required.
public static string CombineName(string first, string last)
{
return first + ” “ + last;
}
Now it’s much easier to call our method. We can get rid of the variable declaration all together. Then, instead of referencing an instance of our class, we reference the class name itself. Three lines of code is reduced to:
string fullName = StaticTest.CombineName(“Arcane”, “Code”);
Notice that the st.CombineName became StaticTest.CombineName. I find that when working with new developers this becomes the most confusing thing about static methods, namely you use the class name instead of a variable when addressing static methods of the class.
Static methods do have a few restrictions. First, they are not allowed to reference any of the class’s variables or properties. This makes sense, as they are running outside of a specific instance of the class. They also cannot use the “this” keyword. Again, this makes sense as this refers to a specific instance (i.e. an object) of a class, and inside a static method there is no instance to access.
The .Net Framework is loaded with static methods, take the string for example. Type in string and hit the period, an you’ll be amazed at how many methods appear. All of these are static methods that are part of the string class.
When writing your methods, take a look and see if they could be implemented statically. If you don’t have to reference other variables or properties of the class, you may have a good candidate for a static method.
One thought on “Static Methods”