Saeed
Saeed

Reputation: 195

nameof in attribute

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.

Upvotes: 4

Views: 4117

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460238

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() { }  
}  

Upvotes: 8

Rowland Shaw
Rowland Shaw

Reputation: 38129

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)

Upvotes: 1

Related Questions