Saturday 18 August 2018

C#: static variables

Static variables are called class level variables. As we know, instance variables are associated with object, whereas class variables associated with class, i.e, available for all objects.

Syntax
static dataType variableName;

Example
static int count;

Static variables are accessed by using class name.

Syntax to access static variable
ClassName.variablename

Program.cs
using System;

class Person
{
    public static int count = 0;

    public Person()
    {
        count++;
    }
}

class Program
{

    static void Main(string[] args)
    {
        Person personA = new Person();
        Person personB = new Person();

        Console.WriteLine("Total objects : {0}", Person.count);

        Person personC = new Person();
        Person personD = new Person();

        Console.WriteLine("Total objects : {0}", Person.count);
    }

}


Output
Total objects : 2
Total objects : 4





Previous                                                 Next                                                 Home

No comments:

Post a Comment