2

I'd like to use a ObsoleteAttribute with a custom const message in order to avoid copy/pasting the message everywhere. For example here is my class:

[AttributeUsage(AttributeTargets.Property)]
public class MyObsoleteAttribute : Attribute
{
    private const string CustomMessage = "This is a custom warning message";
    public MyObsoleteAttribute()
    {
        Console.WriteLine(CustomMessage);
    }
}
    
public class MyClass
{
    [MyObsolete]
    public string? Foo { get; set; }
    
    [MyObsolete]
    public string? Bar { get; set; }
    
    [MyObsolete]
    public string? FooBar { get; set; }
}

I'd like to receive a warning in JetBrains Rider (or Visual Studio) when using such property in the same way as the Obsolete attribute with my CustomMessage.

I try overriding ObsoleteAttribute but it is sealed.

For example the following code should raise a warning (compile time) telling me "This is a custom warning message".

var myClass = new MyClass();
var foo = myClass.Foo;
var bar = myClass.Bar;
var fooBar = myClass.FooBar;

I looked here but I couldn't find exactly an answer to this case: the closest answer is this but it gives me warning on the property and not when using them.

Rowandish
  • 2,655
  • 3
  • 31
  • 52
  • 3
    Why not use `[Obsolete(ClassName.ConstantMessage)]`? – Klaus Gütter Dec 13 '22 at 14:20
  • Does this answer your question? [Custom Compiler Warnings](https://stackoverflow.com/questions/154109/custom-compiler-warnings) – Bassinator Dec 13 '22 at 14:27
  • @Bassinator very similar but I couldn't find exactly: the closest answer is https://stackoverflow.com/a/154254/2965109 but it gives me warning on the property and not when using them – Rowandish Dec 13 '22 at 14:38
  • Well, you can always use the solution that @KlausGütter recommended, which is probably what I would do in your situation. – Bassinator Dec 13 '22 at 14:39
  • @KlausGütter You're right. I'd like to avoid the copy-pasting of "(ClassName.ConstantMessage)" using only an attribute but if it is impossibile your comment is the best way to have such behaviour. You can add it as an answer and I'll mark it as correct. – Rowandish Dec 13 '22 at 14:42

1 Answers1

1

You could define a string constant

public class ObsoleteReasons
{
    public const string Reason1 = "Don't use this";
}

and use it in the attribute

[Obsolete(ObsoleteReasons.Reason1)]
Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36