CodeBlanks Logo Icon CodeBlanks

Static methods

C# course · Intermediate · Lesson 31/116

Learn static methods and how to call them without an instance.

Static methods

A static method is called through the class name and does not need an instance. It cannot touch instance fields; it can only use static fields.

To define one, write static before the return type: public static int Square(int n). To call it, write MathHelper.Square(5). Helper operations, math calculations and conversions are good candidates for static methods.

When to use a static method?

A static method suits operations that don't need instance state. If a method only looks at its parameters and the class's static members, it can be static.

Examples: int.Parse("42"), Math.Max(3, 5), string.IsNullOrEmpty(s). None of these need an object instance. On the other hand, a method that reads an Account object's Balance field must be an instance method.

Exercise Squaring helper

Add a public static int Square(int n) method to MathHelper. Its body returns n * n. In Main, call MathHelper.Square(5) and print the result.

Show example solution
Add `public static int Square(int n) { return n * n; }` to MathHelper. In Main write `Console.WriteLine(MathHelper.Square(5));`.
Example solution:
using System;

class MathHelper
{
    public static int Square(int n)
    {
        return n * n;
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(MathHelper.Square(5));
    }
}

Test yourself

  1. Fill in the blank: static method declaration

    class MathHelper
    {
        public ____
        {
            return n * n;
        }
    }
    Show answer
    class MathHelper
    {
        public static int Square(int n)
        {
            return n * n;
        }
    }
  2. Which statement is correct?

    • A static method can only access static members.
    • A static method can access instance fields.
    • A static method can only be called via an instance.
    • A static method can be a constructor.
    Show answer

    A static method can only access static members. — Correct. A static method cannot touch instance members, only static ones.

  3. Match: static method calls

    Math.Max(3, 5)
    larger of two numbers
    int.Parse("42")
    parses string to integer
    MathHelper.Square(5)
    computes the square
    string.IsNullOrEmpty(s)
    checks for empty string

All lessons in Intermediate