0

I am trying to check if a variable has a TextArea attribute, but even if it does it still returns false.

What am I doing wrong here?

public class Product
{
    [SerializeField] string ID;
    [SerializeField] string Name;
    [TextArea(4, 8)]
    [SerializeField] string Description;
    [SerializeField] double Price;
}

Product product;

public void GetProperties()
{
    PropertyInfo[] properties = product.GetType().GetProperties();
    foreach (PropertyInfo property in properties)
    {
        Debug.Log(Attribute.IsDefined(property, typeof(TextAreaAttribute)));
    }
}
What
  • 47
  • 4
  • Not sure if it's a duplicate, but this should answer your question: https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property – madreflection Oct 02 '20 at 19:17
  • Or this: https://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-3-0 – madreflection Oct 02 '20 at 19:20
  • Yeah it's okay, just figured it out. I use GetProperties(), but I need to use GetFields() instead.Now it works! – What Oct 02 '20 at 19:22

2 Answers2

0

I needed to use GetFields() rather than GetProperties().

What
  • 47
  • 4
0

As others said, TextArea is a field. You should use something like this:

var fieldsWithTextAreaAttribute = typeof(Product)
    .GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
    .Where(f => f.GetCustomAttribute<TextAreaAttribute>() != null)
    .ToList();

This will give you all fields annotated with TextArea. Then you can write GetFields() like this:

using System.Reflection;
using System.Linq;
using System.Collections.Generic;

public List<FieldInfo> GetFieldsWithTextArea()
{
    return typeof(Product)
        .GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
        .Where(f => f.GetCustomAttribute<TextAreaAttribute>() != null)
        .ToList();
}
ndogac
  • 1,109
  • 4
  • 14