How to decide between C# static and non-static methods?

前端 未结 11 954
闹比i
闹比i 2020-12-24 03:35

[Edit]

My original-question was \"Why to decide between static and non-static? Both do the same...\"

Unfortunately it was edited to a C#-specific question wh

11条回答
  •  庸人自扰
    2020-12-24 04:23

    KISS. If you don't have to call a constructor, even better.

    Also, a method being static should tell you a little about how the function operates:

    • It doesn't operate on variables outside of what's passed to it.
    • It doesn't require any memory other than when the method is called (not counting what is returned from the function)

    There are some other important things to note:

    • Static methods in some instances (Java) are not able to be overridden/subclassed, so they are better suited for cases where the implementation will not need to change.
    • Some would argue that static methods are intrinsically difficult to test.

    I would also refer to this thread, and a simple google search which frankly provides copious amounts of discussion on this very topic.

提交回复
热议问题