TheHvidsten
TheHvidsten

Reputation: 4448

Name of a property as input to attribute constructor

I have a custom attribute and I would like it to have the name of a property as input. Because the name is a string it is a valid input type (as attributes are quite limited as to what they can have as input to their constructors). But how can I accomplish this?

Take this example code:

public class MyCustomAttribute : Attribute {
    public MyCustomAttribute(string propertyName) {}
}

public class Foo {
    public bool MyCustomProperty { get; set; }

    [MyCustom(SomeMagicAppliedToMyCustomProperty)] // I want the attribute to receive something along the lines of "Foo.MyCustomProperty"
    public void Bar();
}

How can I accomplish this with the limitations to what an attribute can receive in its constructor?

Upvotes: 3

Views: 3917

Answers (4)

ghostJago
ghostJago

Reputation: 3434

I've used this in an MVC5 application with C#6

private const string jobScheduleBindingAllowed = nameof(JobSchedule.JobId) + ", " + nameof(JobSchedule.Time) + ", " + nameof(JobSchedule.EndTime) + ", " + nameof(JobSchedule.TimeZoneId);

Then when I want to specify the bindings that are valid for the model:

[HttpPost]
public ActionResult CreateJobSchedule([Bind(Include = jobScheduleBindingAllowed)]JobSchedule jobSchedule)
{
    // stuff
}

Slightly cumbersome but better than having magic strings everywhere and is type safe so that errors due to renames can be caught at compile time.

Upvotes: 0

samee
samee

Reputation: 156

You can also use CallerMemberNameAttribute https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx

public CustomAttribute([CallerMemberName] string propertyName = null)
{
    // ...
}

Upvotes: 3

samee
samee

Reputation: 156

There's a new feature in c#-6.0 nameof() that gives the name of the particular property, variable, class etc as a string,

http://www.c-sharpcorner.com/UploadFile/7ca517/the-new-feature-of-C-Sharp-6-0-nameof-operator/ https://msdn.microsoft.com/en-us/magazine/dn802602.aspx

Upvotes: 5

VitaliG
VitaliG

Reputation: 52

This is not possible. The attributes can accept only constants, just put your MyCustomProperty name in quotes into the Attribute.

Upvotes: 3

Related Questions