Reputation: 21611
The way I understand it, having a member variable declared as static in a no-static class causes that member variable to be unique no-matter the number of instances of that class.
Now, what happen to a static method declared in non-static class? And (Most importantly), what the point of declaring a static method in a non-static class?
Thanks for helping
Upvotes: 7
Views: 568
Reputation: 11576
You need static methods in non-static classes f.e. for the factory pattern (if the class is a factory for itself, as pointed out by Jaco Pretorius):
MyClass newInstance = MyClass.Create();
Or if you want to create helper methods. F.e. you could write an FTP-Class which is fully working, with Connect()
, SendCommand()
, ReceiveAnswer()
, Disconnect()
etc., but you want to allow the user to easily upload one file, without the need to implement the whole procedure:
MyFTPClass.UploadFile("username", "password", "pathToFile");
Upvotes: 5
Reputation: 1492
It would be impossible to implement the Singleton pattern without being able to declare a static method (and private member variable) on a non-static class.
See Singleton
Upvotes: 3
Reputation: 100638
It's useful for creating factory methods which are not members of any object but which need access to the internals of an object in order to initialize it.
Upvotes: 5
Reputation: 22442
As ck said, it can be methods that has something to do with the type. It is important to remember that this will be a utility function, that will not be able to access any member variables in the type/class, since it may be called directly without having any instance of the class. If you try to define a static method that accesses a member variable (or non-static method), you will actually get a compiler error.
Upvotes: 1
Reputation: 3012
For example you have a class for example Bank_Account
in which you want to calculate the number of object created for that class.
So, you have one static field say count
. Then when you initialize any object of class Bank_Account
then you need to increment the field which stores the number of objects created for this class, the method incrementing this static variable is static as it is same for all the objects created for this class.
Upvotes: 2
Reputation: 43311
Class method which works only with its parameters, doesn't call any instance methods and doesn't work with any instance members, may be declared as static. Actually, it should be declared as static, for better performance, since static method doesn't require "this" pointer.
Consider small function which belongs to class, makes some calculations with its parameters and returns calculated value. This function should be static.
Upvotes: 4
Reputation: 46415
If the method has something to do with the type but not the instance then it can be static.
DateTime.Parse
and Int32.Parse
are examples.
Upvotes: 21