Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
114 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...