Search code examples
c#nameof.net-attributes

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.


Solution

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