Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

C#: static methods

As we know instance methods are associated with an Object, where as class methods are associated with class.

Syntax
 accessModifier Static dataType methodName(parameters){
    }

Example
Public static int getNoOfEmployees(){

}

Static methods called with class name.

Syntax to call class Methods
ClassName.methodName();

Program.cs
using System;

class Person
{
static int count = 0;

public Person()
{
count++;
}

public static int totalPerson()
{
return count;
}
}

class Program
{

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

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

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

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

}


Output
Total objects : 2
Total objects : 4

Points to Remember
a.   You can't call instance method from static method.
b.   Static methods can't access instance variables


Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

C#: static methods

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×