2

I want to mark a method as Obsolete only for callers from out of its class, while letting methods in its class call it without a warning.

Is that possible?

ispiro
  • 26,556
  • 38
  • 136
  • 291
  • https://stackoverflow.com/questions/983030/type-checking-typeof-gettype-or-is – mer063 Sep 19 '22 at 19:38
  • 1
    No. The `ObsoleteAttribute` cannot be applied conditionally. It's either obsolete or it's not. Compile-time warning directives also can't be applied conditionally. Just add a helpful description in the workaround text indicating it will be changed from `public` to `private` in the future (or whatever you're planning on doing with it). – Jesse Sep 19 '22 at 19:40
  • I'm not sure why you would need to do this. Can you give an example where this is needed? Is suppressing the warning on a particular line an option? – gunr2171 Sep 19 '22 at 19:45

1 Answers1

7

You could extract the method content to a new private method. Internally you would use the private one.

public class YourClass
{
    [Obsolete]
    public void YourMethod()
    {
        YourMethodLogicExtractedToPrivateMethod();
    }

    private void YourMethodLogicExtractedToPrivateMethod()
    {
        //...
    }
}
Ricardo Valente
  • 581
  • 1
  • 10
  • 14
  • 1
    This is a good workaround. Thanks. I'm accepting for now, unless someone comes around with a way to achieve a private Obsolete after all. – ispiro Sep 19 '22 at 19:47
  • 1
    @ispiro There's none. Your best option is to either use a private method for obsolete methods and private backing fields for obsolete properties, or to suppress the warning. – 41686d6564 stands w. Palestine Sep 19 '22 at 19:51