Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of property which our attribute is set?

I'm going to do this without passing any parameter to attribute! Is it possible?

class MyAtt : Attribute {     string NameOfSettedProperty() {         //How do this? (Would be MyProp for example)     } }  class MyCls {     [MyAtt]     int MyProp { get { return 10; } } } 
like image 656
Sadegh Avatar asked Jan 05 '11 17:01

Sadegh


People also ask

How to set attribute in C#?

In C#, you specify an attribute by placing the name of the attribute enclosed in square brackets ([]) above the declaration of the entity to which it applies. [Serializable] public class SampleClass { // Objects of this type can be serialized. }

How would you determine if a class has a particular attribute?

The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);

What is C# attribute purposes of attributes?

Advertisements. An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute.


1 Answers

Using CallerMemberNameAttribute from .NET 4.5:

public CustomAttribute([CallerMemberName] string propertyName = null) {     // ... } 
like image 94
tukaef Avatar answered Sep 21 '22 18:09

tukaef