Lesson Weekend

So far we have been working with methods that are attached to specific instances of an object. For instance, each Car object has a WorthBuying() method. They also have getter and setter methods as well.

These kinds of methods are known as instance methods.

However, we can also create methods that are called on the class itself. These are called static methods. For instance, if we want a method that returns a random Car from our dealership, we could have a .GetRandomCar() method. However, it wouldn't make sense to call that method on a specific instance of a Car. A single car has no idea about the other cars on the lot. This method that could apply to any car and has nothing to do with a specific car.

Let's add a static method to our Car class to experiment.

    public class Car
        public static string MakeSound(string sound)
            return "Our cars sound like " + sound;

Note that we use the keyword static to denote a static method.

To invoke our new method, we call Car.MakeSound("bang"). Considering the quality cars at our dealership, we could easily make our cars squeal, hiss, or hum.

If each individual car has its own unique sound, we could make it an instance method instead, but for the purpose of this example, we are assuming that all of Lonny's Lemons make a banging noise.

Our Car class can produce either instances or static methods.

Some classes, though, are used as libraries. A library is a class or group of classes which represent an organized body of logic. These libraries might be made up entirely of static methods.

For example, .NET has a Math library. This library exists in the System namespace and contains static methods for mathematical calculations. Options range from simple actions like Round() or Max() to more complex actions like Acos() and Cosh(). We may never have a need to compute the hyperbolic cosine of angle, but the functionality exists within the Math library.

Here's how we would find the square root of a number using the Math library:


Notice that we didn't need to create a new instance of the Math class. Instead, Sqrt() is called on the Math class itself.

Try experimenting with static methods in your own projects!


Instance method: Called on an instance of a class.

Static method: Called on the class itself. Here's an example:

public static string AStaticMethod(string arg)
  // Code goes here.

Lesson 8 of 10
Last updated more than 3 months ago.