1

So I have an Attribute that I am putting on various fields.

Inside of the instance of the Attribute class, I would like to find out the value of the field it was placed on. Is that possible?

This seems like it shouldn't be terribly hard, but I seem to see no answers anywhere.

Here is a rough example of what I want:

[AttributeUsage(AttributeTargets.Field)]
public class AssetRestriction : Attribute
{
    public bool ValidateAsset(Object obj)
    {
        return obj is -Type of the Field which this attribute is on-
    }
}

These attributes are used to extend another closed system, so I don't have access to what called the ValidateAsset method to also pass in the field.

rygo6
  • 1,929
  • 22
  • 30
  • 2
    Attributes are for other code to consume. They themselves are dummy data storages. You access field values from the [code that uses your attribute](https://stackoverflow.com/q/2281972/11683), which should be outside of the attribute. Having found fields with your attributes in that way, you add a single line to [retrieve the value](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.fieldinfo.getvalue?view=netcore-3.1) of the field too. – GSerg Jun 13 '20 at 07:12
  • Regarding your edit - apparently you want your attribute to accept a `Type t` in its constructor, apply it as `[AssetRestriction(typeof(int))] object someField` and then use the stored `typeof(int)` to compare against the `obj`. – GSerg Jun 13 '20 at 07:27
  • That is a viable solution. I was just hoping it could automatically infer the type of the field that it is on. – rygo6 Jun 13 '20 at 22:19

1 Answers1

0

If you have the object of the class then you can do like this using reflection. Other solution can be by passing the property in the attribute constructor it self but it will work only for custom attributes

public void GetFields(object obj)
{
    Type type = obj.GetType();
    foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
    {
        if (Attribute.IsDefined(property, typeof(CustomAttribute)))
        {
            object value = property.GetValue(obj, null);
            if (value == null)
                throw new CustomException(property.Name);
        }
    }
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • `Other solution can be by passing the property in the attribute constructor` - if you pass the name of the property, as string, how is the attribute going to retrieve the instance of the object to get that property from? – GSerg Jun 13 '20 at 07:24
  • I mean you can log in the attribute class – Vivek Nuna Jun 13 '20 at 07:27