Click here to Skip to main content
16,021,115 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What are attributes in C# ?and how attribute helpful for the programmer point of view and for compiler point of view?
Explanation with simple example?
Posted

1 solution

attributes are like properties of the Type or the member. and are not data in an instance.

suppose I have the following classes:

C#
public class UserData1
{
   public string Text { get; set;}
   public string Name { get; set;}
   public string Address { get; set;}
}

public class UserData2
{
   public string Description { get; set;}
   public double Price { get; set;}
   public string StorageLocation { get; set;}
}


and suppose I have a reporting Utility, that wants to print out some of the properties.
I could go by implementing a ReportMe interface for each class, or an interface for each class, that only exposed the properties that I want.
with attributes, I can define

C#
public class ReportableAttribute : Attribute {}


now you can mark classes and properties with this attribute:

C#
[Reportable]
public class UserData1
{
   [Reportable]
   public string Text { get; set;}
   [Reportable]
   public string Name { get; set;}

   public string Address { get; set;}
}

[Reportable]
public class UserData2
{
   [Reportable]
   public string Description { get; set;}
   [Reportable]
   public double Price { get; set;}
   public string StorageLocation { get; set;}
}


now I can query an object, and all it's properties if they have this attribute

C#
public void ReportObject(object target)
{
    bool report = false;
    //check if type is marked as Reportable
    foreach (Attribute a in target.GetCustomAttributes())
    {
    	if (a is ReportableAttribute)
    	{
    		report = true;
    		break;
    	}
    }
    if (report )
    {
    	PropertyInfo[] infos = target.GetType().GetProperties (BindingFlags.Public | BindingFlags.Instance | GetField);
           //check if property is marked as Reportable
            foreach (var propInf in infos)
            {
                foreach (Attribute b in propInf .GetCustomAttributes(false))
                {
                    if(b is ReportableAttribute)
                    {
                         this.Writer.Append(propInf.GetValue(target));
                         break;
                    }
                }   
            }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900