Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
public enum error
      {
          Info = 0,
          Warg = 1,
          ErrMsg = 2
      }


//// case 2,case there shows the following error
// cannot implicitly convert type int to an explicit convertion exits (are you missing a cast)

C#
switch (error)
               {
                   case 0:
                       Travel.ErrMsgLblForeColor = Color.Green;
                       break;
                   case 2:
                       Travel.ErrMsgLblForeColor = Color.Yellow;
                       break;
                   case 1:
                       Travel.ErrMsgLblForeColor = Color.Firebrick;
                       break;
               }

please help me
Posted
Updated 18-Jul-11 7:48am
Comments
[no name] 22-Jul-11 10:53am    
You have defeated the very purpose of Enum in C#. One of the main objectives behind the design of the C# language is to catch as many exceptions during compilation itself, rather that leave it to the runtime to handle. That is why C# compiler does not allow you to compile this code.

Why not

C#
switch(error)
{
  case error.Info: ...
  case error.Warg: ...
  case error.ErrMsg: ...
}
 
Share this answer
 
Comments
walterhevedeich 18-Jul-11 17:50pm    
Good point.
Very bad unsupportable code. Why do you think Color is the same as integer? Why do you use immediate constants instead of enumerations? Imaging you change declaration— Also, you could declare array of colors indexed by values of error severity, instead of switch.

—SA
 
Share this answer
 
Comments
Kim Togo 19-Jul-11 11:39am    
Good advice. My 5.
Sergey Alexandrovich Kryukov 19-Jul-11 16:00pm    
Thank you, Kim
--SA
You should use:
C#
case Info:
    // 
    break;
case Warg:
    //
    break;
case ErrMsg:
    //
    break;

If there is a valid reason to use an int then:
C#
switch ((int)error)
{
    //
}

... but this is rarely needed.
 
Share this answer
 
v2
Comments
#realJSOP 18-Jul-11 14:04pm    
5 - 1st correct answer
walterhevedeich 18-Jul-11 17:50pm    
5ed too.
VJ Reddy 1-Jun-12 19:48pm    
My 5!
Probably best to also include

default:
  throw new ArgumentException("Unexpected value found...");


that way you are more likely to trap scenarios where a new value is added to the error enum in future and you have forgotten to update all your code.
 
Share this answer
 
Comments
DaveyM69 18-Jul-11 17:18pm    
Or better still, an InvalidEnumArgumentException: http://msdn.microsoft.com/en-us/library/97x53xzc.aspx

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