Search code examples
c#code-documentationobsolete

Obsolete attribute - Avoid magic string


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>

Solution

  • 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.";
    }