user1040466
user1040466

Reputation:

Error when creating an enum in C# - "identifier expected"

I have never used enums before i have a problem while creating enums

i want to create an enum in C# which is some thing like

enum e{10:30 a.m.,10:31 a.m.,10:32 a.m.}

but it says identifier expected.. can u help me create it.

Upvotes: 4

Views: 21977

Answers (5)

MyKuLLSKI
MyKuLLSKI

Reputation: 5325

Sure can add attributes:

enum e
{
    [Description("10:30 a.m.")]
    AM1030,    

    [Description("10:31 a.m.")]
    AM1031,

    [Description("10:32 a.m.")]
    AM1032,
}


    var type = e.GetType();
    var memInfo = type.GetMember(e.AM1030.ToString());
    var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    var description = ((DescriptionAttribute)attributes[0]).Description;

Upvotes: 9

Erik Dietrich
Erik Dietrich

Reputation: 6090

I would suggest looking at DateTime: http://msdn.microsoft.com/en-us/library/system.datetime.aspx

Creating an enumeration for possible times of the day is going to be prone to code rot, since you're going to have to change that enum every time you want to support a different minute of the day.

But, if your business logic is really that specific to those three minutes, what you want is something like:

    enum Minute
    {
        TenThirty,
        TenThirtyOne,
        TenThirtyTwo
    }

The enum just takes identifiers, and they have to be a single word with no whitespace.

Upvotes: 3

Koen027
Koen027

Reputation: 863

First of all, enums must be declared at Class-level. Meaning they can't be inside the brackets that enclose your class.

Incorrect:

public class {
    enum myEnum {...}
}

Correct:

enum myEnum {...}

public class {
    ...
}

Second: you can't just write in there and expect it to work. Looks like you're trying to add a time. You'll have to use a datetime object for that. Or a string, if you plan on analyzing it each time you read it out.

Here's an example of an enum linking animal names to numbers:

public enum Pets { None=0, Dog=1, Cat=2, Bird=4, Rodent=8, Reptile=16, Other=32 };

Hope this helps.

Upvotes: -2

Ivo
Ivo

Reputation: 8352

One option will be not to use enums in your case but something like this:

public static class Times {
    public static DateTime AM1030 = new DateTime(1,1,0,10,30);
    public static DateTime AM1031 = new DateTime(1,1,0,10,31);
    public static DateTime AM1032 = new DateTime(1,1,0,10,32);
}

var time = Times.AM1030;

The truth is it doesn't give you any value, because you are hardcoding the values anyway. The best will be giving it a business concept, naming those dates as something (I mean, with a word).

Upvotes: 2

DotNetUser
DotNetUser

Reputation: 6612

You could do

    enum e
    {
       time1,
       time2,
       time3, 
    } 

You cannot have values like 10.30 a.m. as enum types.

Upvotes: 3

Related Questions