Thursday, July 23, 2015

Static class questions

Static Class

 Declared with Static keyword, methods in Static Class are also static along with variables of the class. This class cannot be instantiated, i.e. we cannot have objects of this class. To access methods of this class, you can directly use classname.method. Also this class cannot be inherited.
 Why can we not create an instance of a static class?
You can't really create an instance of a static class for the sheer fact that it is a static class. (This is one of the main features that constitutes a static class)
In C#, static classes can be thought of as being both abstract and sealed, meaning that cannot be created or derived from (this is one of the main features of static classes). Static classes (and methods) work especially well as "factories" as you can use them to create instances of other classes however there will only be a single static "factory" that will actually create the classes. They also shine when used as utility functions since you won't have to create a new instance of them every time that you would need to perform a particular function..
How is memory allocated for static classes?
Memory for static classes is managed by the Common Language Runtime (CLR) within .NET and while there isn't a specific time when the static classes will be loaded into memory, it is guaranteed to be available prior to the first time that they are used. (Exactly when this occurs is compiler-specific)
The memory is allocated within a single address that is referenced every time a call is made to the static class (as opposed to several instances that you might have of non-static classes which would each have its own address in memory).
Why is it stored on the Stack and not the Heap?
Your static class will actually be  stored on the heap and not the stack (only local variables are stored on the stack). Your static class could essentially be thought of as more globally accessible (being that it is "available" throughout the application after it is initialized) and would be stored on the heap.
All reference types and fields (class and member variables) are managed by the heap (strings, objects, basically any reference type) and it won't really matter if they are declared as static or not.

Can “this” be used within a static method?
We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.

No comments:

Post a Comment