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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With