Search code examples
c#pragma

Is there any ways to make `#pragma warning disable` usage more elegant?


I got enabled "treat warnings as errors" option in Visual Studio. And I want to ignore some warnings in places where I know that it's ok. So I use #pragma warning disable but I think that this directive makes my code less readable and noisy.

#pragma warning disable 618
            // explanation here
            var target = new DevelopersAndGroupsCondition();
#pragma warning restore 618
            target.Set( t => t.DevelopersOnly, true );

Maybe there is some more elegant way exisits to ignore this warnings. If that so, please let me know.


Solution

  • There is no other way to disable a build warning on a case-by-case basis. Your only other option is to disable the warning for the entire project by adding 618 to the list of warnings to suppress in your project settings.

    Visual Studio project settings

    All that said, warning 618 is usage of code marked with the Obsolete attribute. If it were me, I'd remove the need to use pragma disable/restore 618 by removing references to obsolete code. When code is marked with the Obsolete attribute, there is typically an updated alternate to use, often indicated by the attribute message. You say you want to "ignore some warnings in places where I know that it's ok". If the code is explicitly marked as obsolete, are you sure it's OK, and if so, how much longer will it be before it's either not OK, or the obsolete code is removed? That's my opinion, anyway.