Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and why is ObsoleteAttribute disallowed for property accessors?

Tags:

c#

attributes

Consider this scenario:

public class C
{
    private int _foo;

    public int Foo
    {
        get { return _foo; }

        [Obsolete("Modifying Foo through the setter may corrupt hash tables.  "
            + "Consider using the method 'ModifyFoo' instead.")]
        set { _foo = value; }
    }

    public C ModifyFoo( int foo )
    {
        // return a new instance of C
    }
}

Which doesn't compile:

error CS1667: Attribute 'Obsolete' is not valid on property or event accessors. It is only valid on 'class, struct, enum, constructor, method, property, indexer, field, event, interface, delegate' declarations.

Applying attributes to specifically the accessors is perfectly fine for any other attribute (provided that AttributeTargets.Method is set up in its usages, which is true for ObsoleteAttribute).

like image 528
Tinister Avatar asked May 12 '10 17:05

Tinister


3 Answers

Clearly it is the compiler explicitly forbidding its use, it is not by accident. Hmya, why? A workaround for a restriction in the compiler seems pretty unlikely. I'd guess they decided to forbid it to avoid confusion to the programmer that gets the warning. Unless the message was well crafted, it would be quite confusing that it would show up inconsistently, depending on the property usage.

like image 130
Hans Passant Avatar answered Oct 29 '22 08:10

Hans Passant


In this case, if you were going to make it obsolete, wouldn't you just not include it? The point of the obsolete flag is to say there is a different (and better way of doing something).

In this case, you would probably want to make the change a breaking change and force people to update the code.

like image 41
kemiller2002 Avatar answered Oct 29 '22 07:10

kemiller2002


Why don't you just modify the property to use the code inModifyFoo?

like image 31
Robert Harvey Avatar answered Oct 29 '22 08:10

Robert Harvey