C# Static Method And Variables

In this article i am explaining what is static method and variable. When you create a function or declare a variable, it doesn’t create instance in a memory until you create object of class. But if you declare any function or variable with static modifier, it directly create instance in a memory and acts globally. The static modifier doesn’t reference with any object.

How to: It is very easy to create static modifier with variables, functions and classes. Just put static keyword before the return data type of method.

namespace Static_Var_And_Function
{
    class NumberPower
    {
        // Create static variable
        public static int number;
        //Create static method
        public static void Power()
        {
            Console.WriteLine("Power of {0} = {1}", number, number * number);
            Console.ReadLine();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a number\t");
            NumberPower.number = Convert.ToInt32(Console.ReadLine());
            NumberPower.Power();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *