Getting Name of particular attribute of a property by using reflection.

By the help of David hayden article http://davidhayden.com/blog/dave/archive/2006/03/07/2876.aspx

I make an attribute class TableAttribute ,KeyAttribute and two of my classes

that is

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]

public class TableAttribute : System.Attribute

{

private string _name;

public string Name

{

get

{

return _name;

}

set

{

_name = value;

}

}

public TableAttribute(string name)

{

_name = name;

}

}

-----------------------------------------------------------------------------------------------------------------------------------

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]

public class KeyAttribute : System.Attribute

{

public KeyAttribute()

{

}

private string _name;

public string Name

{

get

{

return _name;

}

set

{

_name = value;

}

}

private bool _isIdentity;

public bool IsIdentity

{

get

{

return _isIdentity;

}

set

{

_isIdentity = value;

}

}

}

------------------------------------------------------------------------------------------------------------------------------------

[Table("Employee")]

public class Employee

{

private int id;

private string employeeName;

[Key(Name = "employee_id", IsIdentity = true)]

public int EmployeeID

{

get

{

return id;

}

set

{

id = value;

}

}

[Key(Name = "employee_name", IsIdentity = false)]

public string EmployeeName

{

get

{

return employeeName;

}

set

{

employeeName = value;

}

}

}

-----------------------------------------------------------------------------------------------------------------------------

[Table("Customer")]

public class Customer

{

private int id;

private string customerName;

[Key(Name = "customer_id", IsIdentity = true)]

public int CustomerID

{

get

{

return id;

}

set

{

id = value;

}

}

[Key(Name = "customer_name", IsIdentity = false)]

public string CustomerName

{

get

{

return customerName;

}

set

{

customerName = value;

}

}

// Anything...

}

---------------------------------------

Now how can I retrieve the value of the attribute of properties (that is employee_name,employee_id)

I pass Employee in this method

private void PrintProperties(Type type)

{

PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo p in properties)

{

//Response.Write(@"[" + keys.GetValue(0).ToString() + @"]<br />"); //here i want's to get attribute name that is employee_name

Response.Write(@"Name = [" + p.Name.ToString() + @"] Value=[]<br />"); //here i get EmployeeName

}

}




Answer this question

Getting Name of particular attribute of a property by using reflection.

  • Markus H

    Hi Mattias! GetCustomAttributes() return an array. You must check that this array have elements and convert them to desired attribute :)


  • VBFan

    Hi!

    Each PropertyInfo have GetCustomAttributes(), inside them you can search your FieldAttribute.


  • Timothy P

    If I understand the question correctly, you do something like this

    string keyName = ((KeyAttribute)Attribute.GetCustomAttribute(p, typeof(KeyAttribute))).Name;



  • ShawnReed

    Ups You right Mattias, I'm sorry, I was mistaken by fact that you use Attribute class, not PropertyInfo.

    One more rock into .NET architects - two ways to get same functionality.
    I would prefer to have same functionality inside single place. Now I understand why reading names of the upcoming Vista classes took so long time...


  • Alec Yu

    Sergey Galich wrote:
    Hi Mattias! GetCustomAttributes() return an array. You must check that this array have elements and convert them to desired attribute :)

    Right, but if you take a closer look at my code you'll see that I used GetCustomAttribute (which returns a single object), not GetCustomAttributes.



  • Prasad Honrao

    Here is a self-explaining example:


    foreach (PropertyInfo p in properties)
    {
        // Find the KeyAttributes on the current property.
        // Also search this member's chain to find the attributes.
        object[] attributes = p.GetCustomAttributes( typeof(KeyAttribute), true );

        // If there where attributes found, print them.
        if( attributes != null && attributes.Count != 0 )
        {
            foreach( KeyAttribute key in attributes )
            {
                Console.WriteLine( "Property name = '{0}', Keyname = '{1}'", p.Name, key.Name );
            }
        }
        else
        {
            // the current property didn't have KeyAttributes.
            Console.WriteLine( "Property {0} has not KeyAttributes.", p.Name );
        }
    }

     



  • Suresh

    a little more laconic version:

    foreach(KeyAttribute key in p.GetCustomAttributes(typeof(KeyAttribute), true))

    {

    Console.WriteLine(key.Name);

    }

    GetCustomAttributes() will always return an array, empty if no attributes found.



  • Getting Name of particular attribute of a property by using reflection.