Selectively suppress custom Obsolete warnings

C#Visual Studio-2008

C# Problem Overview


I'm using the Obsolete attribute (as just suggested by fellow programmers) to show a warning if a certain method is used.

Is there a way to suppress the warning similar to CodeAnalysis' SuppressMessage at points where the use is justified?

This needs to work for [Obsolete("Some message")] which generates warning 618 and the plain [Obsolete] attribute with no message which generates warning 612.

C# Solutions


Solution 1 - C#

Use #pragma warning disable:

using System;

class Test
{
    [Obsolete("Message")]
    static void Foo(string x)
    {
    }
    
    static void Main(string[] args)
    {
#pragma warning disable 0618
        // This one is okay
        Foo("Good");
#pragma warning restore 0618
        
        // This call is bad
        Foo("Bad");
    }
}

Restore the warning afterwards so that you won't miss "bad" calls.

Solution 2 - C#

The intent is to disable the warning for obsolete usage, regardless of whether the construct is marked with [Obsolete] or [Obsolete("Message")]. So use both CS0612 and CS0618:

#pragma warning disable 612, 618 

...

#pragma warning restore 612, 618 

Solution 3 - C#

Here's how to get the warning/error number in the first place:

  1. Rebuild your project.
  2. Go to the Output window.
  3. Look up the line of the warning/error you want to suppress.
    For example:
    C:\Users\Username\Documents\Visual Studio 2010\Projects\Projectname\Classname.cs(203,7): warning CS0162: Unreachable code detected
  4. Copy the number part after "CS".
  5. Then proceed as Jon Skeet says.

(Better always proceed as Jon Skeet says…)

Solution 4 - C#

You're looking for the #pragma warning disable directive

Essentially you add the following command above the call site in the .cs file.

#pragma warning disable 612
SomeMethodCall

612 is the error message ID for calling obsolete methods

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#JordãoView Answer on Stackoverflow
Solution 3 - C#Aaron ThomaView Answer on Stackoverflow
Solution 4 - C#JaredParView Answer on Stackoverflow