Best Practices for .NET enums.

Naming

In .NET, enums should not have an "Enum" suffix.

 

Enum documentation

Enums should have an API comment according following pattern. 

    /// <summary>
    /// <para>
    /// Defines values that specify the possible ....
    /// </para>
    /// </summary>

 

Unit tests

In .NET internally, enums are normally nothing else than ints. Enum members get numerated ascending (0, 1, 2, 3...) according their appearance in the enum.

This leads to a problem. If we do not exactly specify their values within the code, we will introduce breaking API changes as soon as we add new values somewhere in the middle of the enum because now, all following values get a different number. This is a critical bug in case we store the enum values persistently, such as in a database or on hard-disk.

  

Example:

    public enum Something
    {
        None = 0,
        Any,      // will have value 1
        Other,    // will have value 2
    }

 

    public enum Something
    {
        None = 0,
        Any,         // will have value 1
        BreakingAPI, // will get value 2, breaks API!!!
        Other,       // will now have value 3, API broken!!!
    }

 

So, to avoid such situation, as soon as enums members are defined, they are not allowed to change their values anymore for all time. To ensure that, we write unit tests that check for those values to be correct.

 

    [TestMethod]
     public void Test_Something_ValuesRemainStable()
    {
        Assert.AreEqual(3, Enum.GetValues(typeof(Something)).Length, "There have been enumeration values added or removed. This is a BREAKING API CHANGE! More unit tests are needed.");
 
        Assert.AreEqual(0, (int)Something.None, "The value of the enumeration member has changed. This is a BREAKING API CHANGE!");
        Assert.AreEqual(1, (int)Something.Any, "The value of the enumeration member has changed. This is a BREAKING API CHANGE!");
        Assert.AreEqual(2, (int)Something.Other, "The value of the enumeration member has changed. This is a BREAKING API CHANGE!");
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值