Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nameof in attribute [closed]

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.

like image 387
Saeed Avatar asked Sep 16 '25 13:09

Saeed


2 Answers

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() { }  
}  
like image 168
Tim Schmelter Avatar answered Sep 18 '25 09:09

Tim Schmelter


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)

like image 30
Rowland Shaw Avatar answered Sep 18 '25 08:09

Rowland Shaw