C#: Static members

This entry is part 22 of 71 in the series C#

We have learned that to access the method of an object, we create an instance and use a dot after the instance to access the method.

For example, to access the count method of the class Book:

Book book = new Book();

This implies that we must create an object first before accessing its members.

However we have some examples that used Console.WriteLine to print values to the console. You may have noticed that you could call the WriteLine method without first having to construct a Console object.

How come we do not have to do something like this?

Console console = new Console();
console.WriteLine("blah blah");

C# (and many OOP languages) supports the notion of static members, which are class members that can be called without first instantiating the class.

The WriteLine method in System.Console is static, which explains why you can use it without first instantiating System.Console.

using System;

namespace Math
    class Calculate
        public static int Add(int a, int b)
            return a + b;
        static void Main()
            Console.WriteLine(Calculate.Add(10, 15));

In the above program, have declared Add method as a static member of class Calcuate.  That is why we are able to access the Add method using

Calculate.Add(10, 15)

This is done without using an instance.

Main() is static

In fact, there is another static method in the above program.

The method Main, which acts as the entry point to a class, is static because it must be called before any object is created.



Series Navigation<< C#: Designing a class
C#: Static variables >>

Leave a comment

Leave a Reply