8

I've noticed a variation in how Visual Studio handles the use of code marked with the ObsoleteAttribute.

Assume some code calls a method that is marked with this attribute.

If the attribute was applied like this:

[Obsolete]
void Foo() { ... } 

then Visual Studio will highlight any uses of Foo with a green underline, and they will show up in the error list pane as warnings.

But if you do it like this:

[Obsolete("message")]
void Foo() { ... } 

then VS instead will almost ignore the uses of Foo. There is no warning. If you hover over it, only then would you see that it is "deprecated".

I was surprised by this difference... I haven't been able to find any references explaining why this is (example which does not mention it).

This behavior is not helpful (at least in my situation) because people are actually overlooking these cases and using the deprecated code - despite the point of the message being to help inform them. I'd really like them to see the warning.

Is there a way to get VS to handle both of these cases the same way? i.e., treat them both as normal warnings?

I'm aware there is an overload for the attribute constructor that can force it to be treated as an error, but that's not what I'm asking about.

I'm using VS 2019, .NET472 project.


A comment asked if we have any #pragma lines to disable warnings. This is the single use of pragma in the code:

        #pragma warning disable CS0168
        catch (IOException ex)
        #pragma warning restore CS0168

this obviously does not use Obsolete, so I don't see how it could be related. And CS0168 doesn't seem related to this either.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81

1 Answers1

8

It is the Warning level setting of the Build configuration that drives this behaviour.

When the ObsoleteAttribute is being applied without a message, it results in a CS0612 warning,
which is level 1.

Compiler warning (level 1) CS0612

Whereas the ObsoleteAttribute with a message, results in a CS0618 warning,
which is level 2.

Compiler Warning (level 2) CS0618

Setting your warning level to 1 will ignore CS0618, but restoring it to 4, being the default, will show both as warnings.


enter image description here


[Obsolete] // CS0612
public static void DoSomething() { } 

[Obsolete("obsolete with custom message")] // CS0618
public static void DoSomethingElse() { }

static void Main(string[] args)
{
    DoSomething();
    DoSomethingElse();
}
pfx
  • 20,323
  • 43
  • 37
  • 57