Coder Perfect

Custom Obsolete warnings can be suppressed selectively in C#.

Problem

I’m using the Obsolete attribute (as advised by other programmers) to display a warning when a specific method is utilized.

Is there a technique, similar to CodeAnalysis’ SuppressMessage, to suppress the warning when its use is justified?

This must work for both the [Obsolete(“Some message”)] attribute, which generates warning 618, and the simple [Obsolete] attribute, which generates warning 612.

Asked by Alex

Solution #1

Disable the #pragma warning:

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");
    }
}

After that, restore the warning so you don’t miss any “bad” calls.

Answered by Jon Skeet

Solution #2

Regardless of whether the construct is designated with [Obsolete] or [Obsolete(“Message”)], the goal is to suppress the warning for obsolete usage. As a result, both CS0612 and CS0618 should be used:

#pragma warning disable 612, 618 

...

#pragma warning restore 612, 618 

Answered by Jordão

Solution #3

To begin, here’s how to obtain the warning/error number:

(Always follow Jon Skeet’s advice…)

Answered by Aaron Thoma

Solution #4

The #pragma warning disable directive is what you’re looking for.

In the.cs file, simply add the following command above the call site.

#pragma warning disable 612
SomeMethodCall

For invoking deprecated methods, the error message ID is 612.

Answered by JaredPar

Post is based on https://stackoverflow.com/questions/968293/c-sharp-selectively-suppress-custom-obsolete-warnings