How do do this ( a constant value is expected )
-
Wednesday, September 12, 2007 3:16 PM
I had some constants that worked well in this switch statement. But a better design would be to use them as enum types, as follows, however now the switch cant compile.
public
const string HWPARAMETER = "HWNOPARAMS"; // I want to consolidate these in the enumpublic
enum ioTypes { MANUAL,VIRTUALCH,HWPARAMETER,HWNOPARAMS,TMSTIME}private
void MeasurementAgent(string IOtype){
switch (IOtype){
case ioTypes.HWNOPARAMS.ToString(): // wont compilelocalResults = TMSHardwareSensorRead(mStruct);
break;}
switch (IOtype){
case HWNOPARAMS: // does compilelocalResults = TMSHardwareSensorRead(mStruct);
break;
}
}
All Replies
-
Wednesday, September 12, 2007 3:51 PM
Hello,
Syntax for switch case is as below
Code Snippetswitch ( expression )
case constant-expression : statement
[default : statement]In a case statement you can only give a constant-expression, and it can be of either int or string type.
May be you can think of modifying your code to
Code Snippetprivate void MeasurementAgent(ioTypes IOtype)
{
switch (IOtype){
case ioTypes.HWNOPARAMS:localResults = TMSHardwareSensorRead(mStruct);
break;}
}
Cheers -
Wednesday, September 12, 2007 3:53 PM
One issue is that the underlying type of the enum is an int, getting the "name" associated with it is different.
The second issue is switch will not accept anything that can be variable. The reason for this is that switch is not a search case by case statement, switch performs some hashing to provide quicker reference to the possible cases. In general if there is a method call (ToString()) then it isn't (guarenteed to be) a constant evaluation.
One way to deal with what your optimization is would be to parse the string to the enum then switch on the enum value.
private void MeasurementAgent(string IOtype)
{
ioTypes t = (ioTypes)Enum.Parse( typeof(ioTypes), IOtype );switch (t)
{
case ioTypes.HWNOPARAMS: // wont compile
localResults = TMSHardwareSensorRead(mStruct);
break;
}
}
-
Wednesday, September 12, 2007 4:07 PM
I reckon it's what you are passing as a parameter. Should be something like this i think:
private void MeasurementAgent(ioTypes IOtype)
{
switch (IOtype){
case ioTypes.HWNOPARAMS:localResults = TMSHardwareSensorRead(mStruct);
break;
}
}
reason why it wasn't compiling was because you were comparing a string to a ioTypes.
If you could give us the compile error exactly, i think that'd help out a bit more.
-
Wednesday, September 12, 2007 9:31 PMI agree with this approach. Need to parse the string to enum ioTypes.
-
Saturday, May 10, 2008 11:13 PM
How about if the string is a number like 1 2 3 or has spaces in it. I have a problem My string evaluates to be
1 - critical
2 - High
3 - Low

