Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deriving from Exception classes warning: CA2237: Mark ISerializable types with SerializableAttribute

I derived several classes from various exceptions. Now VS gives warning as in the title of this question.

  1. Could someone explain what implications of suppressing this rule?

  2. Could you explain rule from here saying "Do not suppress a warning from this rule for exception classes because they must be serializable to work correctly across application domains."?

P.S. Well I've got an answer myself. You indeed have to mark exceptions as serializable. They work fine without this attribute in same AppDomain. However if you try to catch it from some other domain, it will have to get serialized in order to get across app boundaries. And that is the main reason I found for this.

like image 916
Nickolodeon Avatar asked Jul 04 '12 10:07

Nickolodeon


2 Answers

This is not exactly a Visual Studio warning, it is a warning produced by the FxCop tool. Which you can run from the VS Analyze menu. FxCop is a static analyzer that looks for common gotchas in a .NET program that a compiler won't flag. Most of its warnings are pretty obscure and are rarely really serious problems, you need to treat it as a "have you thought of this?" kind of tool.

The little factoid it is trying to remind you about here is that the Exception class implements ISerializable and has the [Serializable] attribute. Which is a pretty hard requirement, it makes the base Exception object serializable across app-domains. Necessary because Exception doesn't derive from MarshalByRefObject. And necessary to allow code that you run in another app domain to throw exceptions that you can catch.

So FxCop notes that you didn't do the same for your own Exception derived class. Which is really only a problem if you ever intend to have code that throws your exception run in another app-domain. FxCop isn't otherwise smart enough to know if you do so it can only remind you that it goes wrong when you do. It is pretty uncommon so feel free to ignore the warning when you just don't know yet whether you will or not or if it all sounds like Chinese to you.

like image 101
Hans Passant Avatar answered Nov 20 '22 00:11

Hans Passant


If you're not going to use multiple AppDomain in your application, I think you can ignore it or suppress.

like image 40
abatishchev Avatar answered Nov 19 '22 23:11

abatishchev