Custom Attributes and Reflection in C#


This article covers an overview of Custom Attributes and Reflections. I have also added few samples to illustrate creating custom attribute, And with reflection how to explore them. Using reflection to invoke a method from an assembly.

A Fast-Track Overview of Attributes and Reflection

(1) Overview of Attributes

Attributes associate metadata (declarative information) with the methods, properties, types, classes etc. Once an attribute is associated to c# code, it can be then exposed with the help of Reflection at Run-time. Attributes are of 2 kinders; ready-to-use attributes and custom attributes.

Ready-To-Use attributes

These Attributes are provided by the .Net framework and can be used directly.

Ex:

[Serializable] - determines whether a class is serializable
[AssemblyKeyFileAttribue] - determines the name of the file that contain the strong name
[ServiceContract] - denotes the class to be a part of Service Contract in representing the operations
[DataContract] - denotes the class to be a part of Data Contract in representing the data

Custom attributes

These are developed to provide additional information about underlying C# code. Custom attribute classes can be derieved from System.Attribute base class. We can control accessability of custom attributes by adding following attribute settings...

[AttributeUsage] - It adds the ValidOn, AttributeTargets, AllowMultiple, Inherited parameters. Where, AttributeTargets determines the application element to which this attribute can be applied, AllowMultiple determines whether multiple instances can be specified.

Sample Code: (Creating Custom Attributes)



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BE.Attributes
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true)]
public class MappingInfoAttribute : System.Attribute
{
public MappingInfoAttribute(string fieldName)
{
this.fieldName = fieldName;
}

private string fieldName = String.Empty;

public string FieldName
{
get
{
return fieldName;
}
set
{
fieldName = value;
}
}
}
}



Sample Code: (Consuming Custom Attributes in the code)

Code Snippet..



[MappingInfoAttribute("PK_Member_ID")]
public int PK_Member_ID
{
get
{
return pK_Member_ID;
}
Set
{
pK_Member_ID = value;
}
}




(2) Overview of Reflection

Reflection is a feature of .Net framework, that allows us to obtain metadata information from the loaded assemblies and their members inclusdng custom Attributes. Reflection can also be used to create type instances and invoke their members at run-time. This feature is available in the program by adding System.Reflection namespace

Sample Code: (Obtaining the metadata information at run time)

This sample code exprore the mapping field name for the specific property with the help of Custom attribute "MappingInfoAttribute"



public void InsertCall(D d)
{
Type t = d.GetType();
PropertyInfo[] pi = t.GetProperties();
foreach (PropertyInfo p in pi)
{
Type dtype = pi.DeclarativeType.ToString();
Obect o = pi.GetValue(d, null);
Type ptype = pi.PropertyType.ToString();
string s = pi.Name;

// getting custom attribute information
Object[] oarray = pi.GetCustomAttributes();
foreach ( object obj in oarray )
{
MappingInfoAttribute mia = obj as MappingInfoAttribute;

If ( mia != null )
{
Console.WriteLine("{0} is mapped to {1} ", pi.Name, mia.Fieldame);
}
}
}
}



Sample Code: (Another use of Reflection - Loading assembly to run a method at dynamically



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;

namespace LoadAssembly
{
class Program
{
static void Main(string[] args)
{
System.Reflection.Assembly asm = Assembly.Load("AssemblyToLoad"); // load assembly
Type[] typ = asm.GetTypes(); // get all types to use
MethodInfo mymethod = typ[0].GetMethod("MethodToCall"); // get a method from 1st type
object o = Activator.CreateInstance(typ[0]); // create instance of 1st type
string str = (string)(mymethod.Invoke(o, null)); // call method to pick ret val
Console.WriteLine("Returned message = {0} ", str);
}
}
}



I hope, this article gives you an insight to Attributes and Reflection.

Regards!


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: