What does it mean? Having a non-static class which has for example one static method?
Without creating an instance of that class, we can't use it. But What about its static method?
What does it mean? Having a non-static class which has for example one static method?
Without creating an instance of that class, we can't use it. But What about its static method?
If you have a non-static class with a static method, it means you can use the static method even if you don't have an instance of the class.
The static method can be used without the need of instantiating the class. One common case this is used is when the constructor of a class is private and a static method is provided to return instances, like a factory. For example the Create method:
XmlReader reader = XmlReader.Create("test.xml");
Yes, you can call a static method without creating an instance of a class.
A static method is basically just that: a method which is associated with the type itself, not with an instance of the type. (This counts for structs as well.) The same is true for static fields - again, they're associated with the type rather than one particular instance of the type. The name "static" is somewhat unfortunate in terms of it not really describing the concept well - the VB "Shared" keyword is better in some ways, although it implies that it's shared between all instances rather than not being associated with any instance. (Static members are available whether any instances have ever been created or not.)
Indeed, static methods are often used as an alternative to constructors - e.g. Encoding.GetEncoding
. This allows them to return cached instances, return null if that's particularly useful, or do extra work before/after the constructor code.