Re: 'is' operator is giving compile error when used with switch statem

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



I think its important that we look at why this doesn't work (as it would in
C)

we cannot even get a simpler version of this to work.

bool b = Convert.ToBoolean(args[0]);
bool b1 = Convert.ToBoolean(args[1]);
switch (true) {
case (b) :
break;
case (b1) :
break;
}


in fact we can never put a dynamic entry in as a case .. the reason for this
is that the compiler actually generates a lookup table for these items; they
are not processed as an "if" would be. We can see this by looking at the
following example.

string foo = "";
switch (foo) {
case ("test") :
break;
case ("bar") :
break;
}

which ildasms to ...

IL_0000: ldstr ""
IL_0005: stloc.0
IL_0006: ldstr "test"
IL_000b: ldstr "bar"
IL_0010: leave.s IL_0012
IL_0012: ldloc.0
IL_0013: dup
IL_0014: stloc.1
IL_0015: brfalse.s IL_0034
IL_0017: ldloc.1
IL_0018: call string [mscorlib]System.String::IsInterned(string)
IL_001d: stloc.1
IL_001e: ldloc.1
IL_001f: ldstr "test"
IL_0024: beq.s IL_0030
IL_0026: ldloc.1
IL_0027: ldstr "bar"
IL_002c: beq.s IL_0032
IL_002e: br.s IL_0034
IL_0030: br.s IL_0034
IL_0032: br.s IL_0034
IL_0034: ret

http://benjaminm.net/PermaLink.aspx?guid=10071512-7fa5-43eb-9bbc-5c345d0e13f5
explains more ..

Cheers,

Greg Young
MVP - C#
"Raj" <raj.singh@xxxxxxxxxxxxx> wrote in message
news:66E7C98A-1B98-477B-956A-4E4FD8B000EA@xxxxxxxxxxxxxxxx
public static void HandleException(ref Exception io_exException,
bool
i_blnPropagateException)
{
switch (true)
{
case io_exException is ApplicationHandledException:
{
if (i_blnPropagateException)
{
throw io_exException;
}
break;
}
case io_exException is ApplicationBusinessException:
{
if (i_blnPropagateException)
{
throw io_exException;
}
break;
}
}
}

This function is not compiling coming with error "A constant value is
required". In the function 'ApplicationHandledException' and
'ApplicationBusinessException' are classes inherited from
System.ApplicationException.

Can someone please help me what is the reason and what is the way around?
If
this is not possible what can be the alternative way?



.



Relevant Pages