Hmm, where to start. Ok, the first thing I'll say is you can't do what you're trying to do... I'll carry on with explaining why but sorry if it seems a bit disjointed.
To address your immediate question, you are getting that error message because you're using a type like a variable, just like the error message says. A switch statement is expecting a value, not a type. If you want that to work, you'd need to change it to...
- switch (e.GetType())
-
{
-
case typeof(FileNotFoundException):
-
// do stuff
-
break;
-
}
Now, that still won't compile because a switch statement can only work on constant values of an integral type (things like int, byte, etc... strings count here too). So what you'd need to do is change that switch statement to an if-else-if-else statement, as such...
- if (e.GetType() == typeof(FileNotFoundException))
-
{
-
// do stuff
-
}
-
else if (e.GetType() == <exception type>)
-
{
-
// do stuff
-
}
-
else
-
{
-
// do stuff
-
}
Now, you can do this right as a part of your try/catch block, so you don't really need to set this up yourself, you just catch the exception you want and handle it accordingly. The caveat here is that you have to organize them properly, you catch the specific exceptions first, then the generic exceptions. So, for example...
- try
-
{
-
-
}
-
catch (FileNotFoundException e)
-
{
-
// do stuff
-
}
-
catch (IndexOutOfRangeException e)
-
{
-
// do stuff
-
}
-
catch (Exception e)
-
{
-
// do stuff
-
}
You have to catch Exception last because it's a more general than the other two. This is actually based of inheritance. If you have Visual Studio, you can right-click on the exception type and select "Go To Definition" to bring up the metadata and see the class definition and follow the inheritance chain.
I hope that helps :)