Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 605
Peter Avatar asked Jul 29 '11 00:07

Peter


1 Answers

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.

like image 69
CodeNaked Avatar answered Nov 15 '22 06:11

CodeNaked