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();
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
No comments:
Post a Comment