Peter
Peter

Reputation: 799

Accessing Class and Property name inside an Attribute

Is there any way to access the Class and Property name which you attached an attribute to inside the attribute?

For example

public class User {
    public string Email { get; set; }
    public string FirstName { get; set; }

    [MyAttribute]
    public string LastName { get; set; }
}

And then in the MyAttribute class

public class MyAttributeAttribute {
    public MyAttributeAttribute () : base() {
        string className = /*GET CLASS NAME - should return "User" */
        string propertyName = /*GET PROPERTY NAME - should return LastName*/
    }
}

I know I can pass in the information in the constructor, but hoping there is an easy way somehow to save on retyping info over and over again either via reflection or...

Upvotes: 8

Views: 1832

Answers (1)

CodeNaked
CodeNaked

Reputation: 41393

Sorry, but no that's not possible. You could also have

public class User {
    public string Email { get; set; }
    public string FirstName { get; set; }

    [MyAttrubute]
    public string LastName { get; set; }
}

[MyAttrubute]
public class OtherClass {

    [MyAttrubute]
    public string AnotherProperty { get; set; }
}

The attribute can be created from anywhere. Even the following is a valid way to create an instance:

var att = new MyAttribute();

Your question could be boiled down to "Can I detect where my custom class is instantiated from?". In my last example, StackTrace could probably be used. But with attributes they are being constructed by the .NET runtime, so you would not be able to go that route.

Upvotes: 7

Related Questions