1

I want to mark an old class as Obsolete and redirect to the new class in the Obsolete attribute comment. However, if I write the new class name as a magic string, I won't be able to use the might of IDE.

For example, if I rename my class, I will loose the "link". And the reader won't be able to Ctrl + click on my comment to go to the new class.

The official documentation does seems to say that it is not possible, but I find strange that nobody has this need.

Instead of

// Mark OldProperty As Obsolete.
[ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)]
public static string OldProperty
{ get { return "The old property value."; } }

public static string NewProperty
{ get { return "The new property value."; } }

I would like to be able to write

[ObsoleteAttribute($"This property is obsolete. Use {nameof(NewProperty)} instead.", false)]

As a workaround, I can use the XML doc, but it's not the best way to do it.

/// <remarks>Replaced by <see cref="LoadBrainIndMeasMessTable"/></remarks>
4
  • 6
    "I would like to be able to write ..." -- as of C# 10 (.NET 6), you can. sharplab.io/… Commented Oct 17, 2024 at 7:59
  • 5
    Before C#10, you can write "This property is obsolete. Use " + nameof(NewProperty) + " instead." Commented Oct 17, 2024 at 8:01
  • Thanks! I forgot I was on an old project. I got An attribute argument must be a constant expression, 'typeof()' expression or array creation expression of an attribute parameter type when trying to do so, I did not think to check in later language version. Would you like to write it as an answer so I can accept it as resolved? Commented Oct 17, 2024 at 8:43
  • 1
    As an aside, classes that define attributes by convention always end with "Attribute", but when you use them as attributes, you drop that part of the name: [Obsolete] not [ObsoleteAttribute] Commented Oct 17, 2024 at 10:42

1 Answer 1

6

This is already supported in C# 10 (.NET 6):

public class C
{
    [Obsolete($"This property is obsolete. Use {nameof(NewProperty)} instead")]
    public static string OldProperty => "The old property value.";

    public static string NewProperty => "The new property value.";
}

Before then, string concatenation should work for any C# version:

public class C
{
    [Obsolete("This property is obsolete. Use " + nameof(NewProperty) + " instead")]
    public static string OldProperty => "The old property value.";

    public static string NewProperty => "The new property value.";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.