Making Methods All Static in Class

前端 未结 10 1336
离开以前
离开以前 2021-01-04 12:10

I was told by my colleague based on one of my classes (it is an instance class) that if you have no fields in your class (backing fields), just make all methods static in th

10条回答
  •  Happy的楠姐
    2021-01-04 12:17

    There is very little downside to calling new and constructing a class reference, especially if the class has no state. Allocations are fast in .NET, so I wouldn't use this alone as a justification for a class to be static.

    Typically, I feel a class should be made static if the class has no specific context - if you're using the class just as a placeholder for "utility" methods or non-context specific operations, then it makes sense to be a static class.

    If that class has a specific need for context, and a meaning in a concrete sense, then it probably does not justify being static, even if it has no state (although this is rare). There are times where the class purpose is defined by its reference itself, which provides "state" of a sort (the reference itself) without any local variables.

    That being said, there is a big difference between a static class and a singleton. A singleton is a different animal - you want to use it when you need an instance, but only one instance, of the class to be created. There is state in a singleton, but you are using this pattern to enforce that there is only a single copy of the state. This has a very different meaning, and I would highly recommend avoiding using a singleton just to prevent needing to "call new".

提交回复
热议问题