开发者

default value of enumeration element in c#?

public enum DAYS {
    Monday=1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

Here suppose I want to override default value of enum element as like monday. here as I know that after giving 1 to monday 2 will be default value of tuesday and next one will have 3 or so on,

let's change the scenario

public enum days
{
    monday = 4,
   开发者_开发知识库 tuesday=8,
    wednesday,
    thursday,
    friday=25,
    saturday,
    sunday
}

here what will be value of wednesday,thursday,and saturday,sunday ..?

question 2:

can we assign char and string type of value to the enum element...

question 3:

can we override enum as char or string type ?

like as

public enum name :string
{
    first_name="nishant",
    Last_name = "kumar"
}


  1. Any value you don't specify is 1 higher than the previous one. (Wednesday would be 9, Thursday would be 10, Saturday 26 and Sunday 27.) Note that this even true when the enum is decorated with the [Flags] attribute - you should pretty much always specify the underlying value associated with each name when using [Flags].

    From section 14.3 of the C# 4 spec:

    Otherwise, the associated value of the enum member is obtained by increasing the associated value of the textually preceding enum member by one. The value must be within the range of values that can be represented by the underlying type, otherwise a compile-time error occurs.

  2. No, the valid underlying types for an enum are sbyte, byte, short, ushort, int, uint, long and ulong, as per section 14.1 of the C# spec. It explicitly states:

    Note that char cannot be used as an underlying type.

    (It doesn't mention string here, as it's already said that the underlying type has to be an integral type.)

  3. Irrelevant based on the answer to 2.

Typically if you want to associate an arbitrary string value with an enum value, you should either use a resource file keyed on the enum value's name, or use an attribute (e.g. DescriptionAttribute).


  1. Wednesday will equal 9, Thursday will be 10. Saturday will be 26 and Sunday 27.
  2. No.
  3. No.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜