C# static Keyword

Updated on     Kisan Patel

In C# OOPS, all the members (E.g. variables, methods) of the class are instance members of that class. That means they belong to object being created.

But, Static members belong to the class rather than to individual object.

Static members are defined using static keyword as shown in below example.

class Person
{
    public static int Age = 40;

    public static int Sum(int a, int b)
    {
        return a + b;
    }
}

Static members are accessed with the name of class rather than reference to objects.

classname.static_member_name;

The following example illustrates the rules for accessing static members.

using System;

namespace ConsoleApp
{
class Person
{
    public static int Age = 40;

    public static int Sum(int a, int b)
    {
        return a + b;
    }
}

    class PropertyTester
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Your age is : " + Person.Age);
            Console.WriteLine("The Sum of 10 and 30 is : " + Person.Sum(10, 30));
        }
    }
}

The output of the above C# program…

c-sharp-static-member-demo

In above example, you can see that the Age variable and Sum method are accessed wthout any reference to the object but with the name of the class it belongs.


C#

Leave a Reply