Click here to Skip to main content
15,912,897 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
class Query3
{
    enum Foo
    {
        mon,
        tue
    };

    static void Main()
    {
        Foo f =1;       
        Console.WriteLine(f);
        Console.ReadLine();
    }
}


Hello,
I want to know, why "Foo f=1" is giving Error.
please help.....

Thanks in advance...
Posted

Short answer, 1 isn't of type Foo even though Foo has a value of 1. You aren't a VB dev by any chance? The reason I say this is the enum is 0-based in .net so tue is 1, not mon (which is 0), but I digress. To fix your code is simple:

Foo f =(Foo)1;  



Though there are lots of circumstances where the above is useful, it is more usual to do

Foo f =Foo.tue;
 
Share this answer
 
Comments
walterhevedeich 6-Jul-11 5:56am    
Excellent advice. Have a 5.
Because you didnt cast int to enum. What you need to do first is cast it, like this
Foo f = (Foo)1; 

This however, will give you two because enums are zero based. So you might want to modify your code like this.
C#
enum Foo
{
    mon=1,
    tue=2
};
 
Share this answer
 
You can't directly assign an enum an integer value. Look at this tip. It shows a better way to assign an enum variable to an integer.

Setting Enumerators From Questionable Data Sources (for C# and VB)[^]
 
Share this answer
 
Amruta,

1 is an Integer. And Foo of type Enum.

Can we assign string value into an integer variable without type casting? No.

In same way we cannot do this.

Read Boxing and Unboxing.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900