C#: Is pragma warning restore needed?
If you do not restore the disabling is active for the remainder of the file.
Interestingly this behaviour is not defined in the language specification. (see section 9.5.8) However the 9.5.1 section on Conditional compilation symbols does indicate this "until end of file behaviour"
The symbol remains defined until a #undef directive for that same symbol is processed, or until the end of the source file is reached.
Given the 'pre-processor' is actually part of the lexical analysis phase of compilation it is likely that this behaviour is an effective contract for Microsoft's and all other implementations for the foreseeable future (especially since the alternate would be hugely complex and non deterministic based on source file compilation order)
Let's say I have a private field that is initialized using reflections, the compiler obviously can't find any code directly writing into this field so it will show a warning - that I don't want to show.
Let's also say I have another private field defined 3 lines below the first that I forgot to initialize, if I disable the warning for the entire file this will not trigger a warning.
So, the best usage for #pragma warning is to put a "warning disable" right before the line that causes the warning that I want to suppress and a "warning restore" right after the line so the same condition in a different location in the file will still trigger a warning.
No, you'll find that the compiler will automatically restore any disabled warning once it's finished parsing a source file.
#pragma warning disable 649
struct MyInteropThing
{
int a;
int b;
}
#pragma warning restore 649
In the above example I've turned of warning CS00649 because I intend to use this struct in an unsafe manner. The compiler will not realize that I will be writing to memory that has this kind of layout so I'll want to ignore the warning:
Field 'field' is never assigned to, and will always have its default value 'value'
But I don't want the entire file to not be left unchecked.