Static Variables:
- A value assigned to a static variable will be shared across all instances of the class. On the other hand an instance variable may have different values across every different instance of the class.
- Static variables can be mainly used for initialization purpose.
Static Methods:
- Static methods cannot access non-static class level members and do not have a 'this' pointer. Instance methods can access those members, but must be called through an object instantiation.
- Static methods can be called directly from class name.
- Explanation: So, need to create instance for those classes that contain static methods in it.
- Do not declare or override instance members in static classes.
- Cannot initialize instance variable or class variables in static methods.
- Explanation: if you declare instance variables in static methods. How can you use those variables? No chance to use of it. So not possible to create instance variables in static method.
- Static methods can be used to initialize the variables. But can only be initialize static variables in static methods.
Static Class:
- A class can be declared as static, indicating that it contains only static methods and private constructor.
- Explanation: Static class is also called as sealed class and if you define private constructor inside class then those class is also called as sealed class. If a class contains only static methods it’s better to declare that class as static.
- Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
- It is not possible to create instance of a static class using the “new” keyword.
- Explanation: why means, a static class contains only static methods and static methods can only be called directly by using class name with dot operator. Then what is the use of creating an instance for the static class using “new keyword.
- Static class are Sealed therefore cannot be inherited.
- Static class cannot contain normal methods.
- Explanation: We cannot create an instance for the static class. But normal methods can only be called by using the object of that class.
Static
Constructor:
- You can create a constructor as static and when a constructor is created as static, it will be invoked only once for any number of instances of the class and it is during the creation of first instance of the class or the first reference to a static member in the class.
- Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.
- A static constructor cannot be a parametrized constructor.
- Within a class you can create only one static constructor.
- Explanation: Main reason, Static constructor cannot have parametrized constructor and constructor cannot have return type even “void” also. So, static constructor can have no return type, no parameters.
No comments:
Post a Comment