Static keyword is used to make members static that can be shared by all the class objects.
Static
The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
- class MyClass
- {
- static int X = 10;
- int Y = 20;
- public static void Show()
- {
- Console.WriteLine(X);
- Console.WriteLine(Y); //error, since you can access only static members
- }
- }
Key points about Static keyword
- If the static keyword is applied to a class, all the members of the class must be static.
- Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
- Static constructor can't be parameterized. Access modifiers can not be applied on Static constructor, it is always a public default constructor which is used to initialize static fields of the class.
No comments:
Post a Comment