So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields.
One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example:
var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg");
As for static fields, is creating singelton-objects their best use?
Static methods are usually useful for operations that don't require any data from an instance of the class (from this
) and can perform their intended purpose solely using their arguments.
A simple example of this would be a method Point::distance(Point a, Point b);
that calculates the distance between two points and don't require an instance.
Static fields are useful among others for constants that don't change all that often and are used by all the instances of a class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With