What does the keyword static mean
Static Classes and class members are used to create data and methods that can be accessed without creating an instance of the Class. The keyword Static can be applied to the Classes, field, method, properties, operator, event and constructors.
We can call variables and methods of static classes without creating an instance of the class. That means you cannot use the new keyword to create a variable of the class type. We can call static members and methods directly from classes like the following :
When we declared a variable or method as static, what really happens is that all the instances of the class share the same static variable. That means, where ever we used this class, the class will share the same copy of that variable and methods.
When we try to create an instance of the above class it will generate a compile time error.
The above code generate a compilation error.
When we use static keyword in .Net ?
We can use them when we need to maintain information applicable to the entire class. Static class can contain only static members, that is static methods, static fields, static properties. This is because static class cannot refer to any instance members. Static member belongs to that particular class and not to any object of the class. It is important to note that a static method cannot access non-static fields.
What are static Classes?
Static Classes use the static keyword before a class name and whose objects can't be created. Also it should only have static member variables and methods. They can't be inherited and these classes are sealed by default. Normally it is used to group related static methods in class.
The advantage of static keyword is that it will make your code a bit faster since no object creation is involved.
- Difference between a Value Type and a Reference Type
- System level Exceptions Vs Application level Exceptions
- Difference between sub-procedure and function
- What does the term immutable mean
- this.close() Vs Application.Exit()
- Difference between a.Equals(b) and a == b
- Difference between Hashtable and Dictionary
- Difference between Exception and Error
- C# Dictionary Versus List Lookup Time
- Difference between the Class and Interface in C#
- Why does C# doesn't support Multiple inheritance