+ 4

why static keyword is written in methods (other than Main method)?

30th Sep 2016, 1:38 AM
Aishwarya
3 Respostas
+ 13
A static function, is not associated with the instance of a class unlike regular functions. e.g. class A { public void funcA() { system.Console.WriteLine("A") ; } public static void funcB () { system.Console.WriteLine("B") ; } } When you call these functions, you'll need an instance of Class A to call funcA() , but funcB() can be called without creating any instance since it's static. A instance = new A(); instance.funcA(); //Fine instance.funcB();. //Won't compile A.funcA(); //Won't compile A.funcB(); //Fine Since, main needs to be called directly i.e. without creating any instance of its parent class, therefore it is declared static. Similarly, if there's similar need for other functions too, they are declared static. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine. Note : A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.
30th Sep 2016, 4:20 AM
Nikhil Chandla
Nikhil Chandla - avatar
+ 4
Static keyword use to access class functions, variables by class name without creating an object(instance) of a class. if you don't prefix Static when you declare variable and functions than to access those variables, functions you have to create an object of that class so than by using objects(instance) you can access them. if the class is static than you can not create an object(instance) of a class and than you can access all variables and functions by using class name and dot(.) operator. for example:- fruits.eat (); and than you don't need to prefix static to each variable and functions. if the class is static than all its members by default is static.
30th Sep 2016, 10:00 AM
Paras Jain
Paras Jain - avatar
0
briefly you cannot call any function in( main ) either it has a static keyword
9th Dec 2016, 9:03 PM
Yahia El Tantawy
Yahia El Tantawy - avatar