C# Class - Static Members



We have seen that we need to create an instance of the class before we can use methods inside it. If you try to use a method of the class, it generates an error. The following program will therefore generate and error.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Car
{
    public void xyz()
    {
        Console.WriteLine("Referencedesigner tutorials are very bad");
    }
}  

namespace Printline
{
    class Program
    {
        static void Main(string[] args)
        {
            Car.xyz(); // This will generate an error
                       // Because instance of class Car was not created.   
            Console.ReadLine();
        }
    }
}


There are cases wherre we want to make the method global. We want to access the methods of the class without the need to create an instance of it. To do this we precede the method declaration with the keyword static. Here is the program that will work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Car
{
    public  static  void xyz()
    {
        Console.WriteLine("Learning C# is easy with Reference Designer tutorials");
    }
}  

namespace Printline
{
    class Program
    {
        static void Main(string[] args)
        {
            Car.xyz(); 
            Console.ReadLine();
        }
    }
}



If we run the program we get the following result.
	
Referencedesigner tutorials are very bad



The static methods are kind of global methods to speak in the C or C++ terminology. Let us take a more useful example, where we want to provide a global method to calculate the area of the rectangle.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class rectangle
{
    public static int calculatearea (int x, int y)
    {
        return (x * y);
    }
}  

namespace Printline
{
    class Program
    {
        static void Main(string[] args)
        {
            int length, breadth, area;
            length = 10;
            breadth = 20;
            area = rectangle.calculatearea(length, breadth);
            Console.Write("Area of Rectangle is :");
            Console.Write(area); 
            Console.ReadLine();
        }
    }
}







If you run the above program you get the following output.

	
Area of Rectangle is :200




As you can see you can just call rectangle.calculatearea without the need to create instance of the class. This is helpful in many cases.