Making Methods All Static in Class

前端 未结 10 1367
离开以前
离开以前 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条回答
  •  情深已故
    2021-01-04 12:42

    Utility classes are often composed of independant methods that don't need state. In that case it is good practice to make those method static. You can as well make the class static, so it can't be instantiated.

    With C# 3, you can also take advantage of extension methods, that will extend other classes with those methods. Note that in that case, making the class static is required.

    public static class MathUtil
    {
        public static float Clamp(this float value, float min, float max)
        {
            return Math.Min(max, Math.Max(min, value));
        }
    }
    

    Usage:

    float f = ...;
    f.Clamp(0,1);
    

提交回复
热议问题