How do I get the count of attributes that an object has?

39,036

Solution 1

Since the attributes are on the properties, you would have to get the attributes on each property:

Type type = typeof(StaffRosterEntry);
int attributeCount = 0;
foreach(PropertyInfo property in type.GetProperties())
{
 attributeCount += property.GetCustomAttributes(false).Length;
}

Solution 2

Please use the following code:

Type type = typeof(YourClassName);
int NumberOfRecords = type.GetProperties().Length;

Solution 3

This is untested and just off the top of my head

System.Reflection.MemberInfo info = typeof(StaffRosterEntry);
object[] attributes = info.GetCustomAttributes(true);
var attributeCount = attributes.Count(); 

Solution 4

Using Reflection you have a GetAttributes() method that will return an array of object (the attributes).

So if you have an instance of the object then get the type using obj.GetType() and then you can use the GetAttributes() method.

Share:
39,036
IntrepidDude
Author by

IntrepidDude

Updated on July 09, 2022

Comments

  • IntrepidDude
    IntrepidDude almost 2 years

    I've got a class with a number of attributes, and I need to find a way to get a count of the number of attributes it has. I want to do this because the class reads a CSV file, and if the number of attributes (csvcolumns) is less than the number of columns in the file, special things will need to happen. Here is a sample of what my class looks like:

        public class StaffRosterEntry : RosterEntry
        {
            [CsvColumn(FieldIndex = 0, Name = "Role")]
            public string Role { get; set; }
    
            [CsvColumn(FieldIndex = 1, Name = "SchoolID")]
            public string SchoolID { get; set; }
    
            [CsvColumn(FieldIndex = 2, Name = "StaffID")]
            public string StaffID { get; set; }
        }
    

    I tried doing this:

    var a = Attribute.GetCustomAttributes(typeof(StaffRosterEntry));
    var attributeCount = a.Count();
    

    But this failed miserably. Any help you could give (links to some docs, or other answers, or simply suggestions) is greatly appreciated!

  • EAmez
    EAmez about 7 years
    Simple and smart. +1
  • Iorek
    Iorek about 5 years
    This is now >>> Object .GetType().GetProperties().Length(); - stackoverflow.com/questions/42029808/…
  • OuttaSpaceTime
    OuttaSpaceTime almost 3 years
    look here for an example on how GetAttributes() can be used.