• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

C# Switch Statement Goodness...

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

YellowDart

Member
Joined
Sep 25, 2003
Location
Mesa, AZ
So question for some of you knowledgeable types out there...

I'm working on tweeking an exception handler class I'm writing. I originally implemented it in a longer if statement, and am working on refactoring it over to a switch statement. The compiler, however, doesn't seem to like what I'm telling it. Here's what I've got so far:

Code:
public sealed class ExceptionHandler
    {
        private const string FORMAT = "Format Exception";
        private const string OVERFLOW = "Overflow Exception";
        private const string EXC = "Other Exception";
        
        /// <summary>
        /// Playing with switch statements...
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>

        public static string ValidateException(Exception ex)
        {
            /*  Here's the effect I'm looking to duplicate via my switch statement:

            if (ex is FormatException)
            {
                return FORMAT;
            }
            else if (ex is OverflowException)
            {
                return OVERFLOW;
            }
            else
            {
                return EXC;
            }
            */

            switch (ex) // Compiler is looking for a different datatype, 
                        // most primitive types and enum types are ok...
                        // Might want to look at casting to a primitive or enum.
            {
                case (ex is FormatException):
                    return FORMAT;
                    break;
                case (ex is OverflowException):
                    return OVERFLOW;
                    break;
                default:
                    return EXC;
                    break;
            }
        }

So like my comments say: The compiler error I'm getting is telling me that C# is looking for a different type in my switch statement. I'm understanding, if I want to go this route, I may need to cast my exception object to something else, either a primitive type (byte, long, int, etc) or cast to an enum.

Any thoughts? Am I barking up the right tree?
 
I'm not sure of the issue because I don't know C# but when you RETURN from a function, you are essentially "breaking" so the break statement isn't even needed in your case once you return.

Also where are you defining FORMAT/EXC/etc? are these Global variables?

Doing a quit google search it looks like your violating a rule that the case (n) where n has to be a constant expression, I'm not sure if yours is a valid constant expression.

C# Tutorial 1.1 - Conditional switch Statement

The conditional statement switch, selects one of a number of possible statements for execution based on a value of an expression. The switch statement takes the following form:

switch( expression )
{
case constant-expression:
statement
jump-statement
[default:
statement
jump-statement]
}

You could I think use logic to determine a number you want to assign each type of expression or make an enumeration and it may work, and based on the number return a new instance of the expression whatever it may be.
 
Last edited:
technoViking is definitely onto something with the FORMAT/OVERFLOW/EXC return statements. You are returning a string but have not put double-quotes around those strings therefor the compiler is looking for objects of those names to return at run-time. Being that you have not defined those objects, the compiler is telling you there is an error.
 
I don't know much about C# but as part of .NET it should be able to use the Try, Catch functionality.

Code:
Try

        Catch ex As FormatException
            Debug.WriteLine("Format Exception")

        Catch ex As OverflowException
            Debug.WriteLine("Overflow Exception")

        Catch ex As Exception
            Debug.WriteLine("Other Exception")

End Try

That is from VB, so you may have to translate it to C#. But using the multiple catch statements is functionally the same as your case statement.
 
@ Techno & Taco:

I've defined those three strings at the top of my class. They are above my static method in my original post... right under my class definition. They're private member constants:

Code:
public sealed class ExceptionHandler
    {
        private const string FORMAT = "Format Exception";
        private const string OVERFLOW = "Overflow Exception";
        private const string EXC = "Other Exception";

...

I've thought about going with an enum something along the lines of:

Code:
public enum ExceptionTypes : int
{
    Format = 1,
    Overflow = 2,
    Other = 20  // To leave room if I need to add more exception types later.
}

Then in my switch, I could maybe use the traditional...

Code:
ExceptionTypes types = new ExceptionTypes();

switch (types)
{
    case1: 
        return FORMAT;
        break;
    case2:
        return OVERFLOW;
        break;
    default:
        return EXC;
        break;
}

Also, regarding the need for "break;", unless I'm mistaken, C# requires a break; for each case. I'll have to look at that again, just to be sure.

As far as doing this all in a try/catch block goes, I'm actually calling this static method from a try/catch block. I've got a facade class I'm using to encapsulate reading user input and passing to another class if everything is kosher. If there is an exception to return, I call this static method from my catch block to return a custom error message based on the exception type.

/edit

My struggle here will be translating an Exception object into my enum type. Might just be easier to stick with my if's here, since an if can handle non-primitives well.
 
Last edited:
One further quick update. It does appear that C# requires the "break;" expression in each case inside a switch block.
 
switch (ex.GetType().ToString())
{
case "System.FormatException" :
return FORMAT;
break;

case "System.OverflowException" :
return OVERFLOW;
break;

default:
return EXC;
break;
}



not sure if the above will work as I don't have visual C# on my system right now, but this may do what you want with some tweaking
 
Hrm... I may just have to give that a shot. I can't believe I haven't tried that yet. I'm pretty sure I tried...

switch (ex.GetType())

But I must have spaced and forgot to try calling ToString(). I'll give it a shot when I get home tonight. ;)

/edit

Thinking about it, I may need to convert the exception types to strings as well... but that may work. I'll post again when I try it at home. Thanks!
 
Last edited:
Nice one spagnitz,

That will work I think.

The reason is, is because you were not using a constant expression you see, he's using

case "System.OverflowException" :
"System.OverflowException" is a constant expression, its not going to change ever, just like an integer, like case 1

You were doing:
case (ex is FormatException):
ex is FormatException might be true, might not be true, so its not constant.

I haven't used a switch statement in awhile so I could be wrong but it looks like his solution would work great.
 
Nice one spagnitz,

That will work I think.

The reason is, is because you were not using a constant expression you see, he's using

case "System.OverflowException" :
"System.OverflowException" is a constant expression, its not going to change ever, just like an integer, like case 1

You were doing:
case (ex is FormatException):
ex is FormatException might be true, might not be true, so its not constant.

I haven't used a switch statement in awhile so I could be wrong but it looks like his solution would work great.

I'm pretty sure that's the issue. The switch/case statement, unlike an if statement, takes non-boolean input and evaluates it to boolean on its own, so if you try and put in a boolean statement like "case (ex is FormatException)", the program won't work as expected because the switch/case statement will be looking for ex == true (if ex is FormatException) or ex == false (if ex is not FormatException). Of course, that means that ex can never equal true, because that would mean it would have to simultaneously equal FormatException. Anyway, I'm probably rambling a bit, but hopefully that explains the issue a bit better.
 
Back