3

Considering Myatt attribute and MyObj class, it is somehow strange that ObjName property is known in scope of Myatt attribute. Isn't it?

[AttributeUsage(AttributeTargets.Property)]
public class MyAtt : Attribute
{
    public MyAtt(string name)
    {
        this.Name = name;
    }

    public string Name
    {
        get; set;
    }
}

public class MyObj
{
    [MyAtt(nameof(ObjName))] //Can access to ObjName?!
    public int ObjID
    {
        get;
        set;
    }

    public string ObjName
    {
        get;
        set;
    }
}

Update :

Sorry, I'm wondering why the first case is not possible and the second is possible.

1. [MyAtt(nameof(this.ObjName))] 
2. [MyAtt(nameof(ObjName))] 

I get it now. Thanks.

Saeed
  • 185
  • 2
  • 13

2 Answers2

8

It's good that it's supported there, isn't it? So no, it's not strange.

Documentation mentions an Attribute example as key use case:

[DebuggerDisplay("={" + nameof(GetString) + "()}")]  
class C {  
    string GetString() { }  
}  
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

If you consider nameof(...) as syntactic sugar, then it's not strange - your attribute takes a string, and the compiler works out that string at compile time (taking into account any renames as a result of refactoring)

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166