Thursday, 1 September 2016

Runtime type ID and Reflection




Runtime type ID is the mechanism that lets you identify a during the execution program. Reflection is the feature that enables you to obtain information about a type with the help of this you can create the object at runtime. Attribute describes a characteristic of some element in C#.


Runtime Type Identification (RTTI) allows the type of an object to be determined during program execution.
C# includes three type of RTTI : is , as and typeof.

is Operator is use to determined whether on object is of a certain type
    expr is type

class A{}
class B :A{}
class Demo
{
  public static void Main(String[] args)
   {
     A a=new A();
     B b=new B();
         if(a is A) {
    Console.WriteLine(“Display A”);
}
         if(b is B) {
Console.WriteLine(“Display B”);
}
        }
}

Using as Operator
Sometimes you will want to try a cast at runtime but not raise an exception if cast fails so you can use as operator.
    expr as type
class A{}
class B :A{}
class Demo
{
  public static void Main(String[] args)
   {
     A a=new A();
     B b=new B();
     b = a as B;

         if(b==null) {
    Console.WriteLine(“Cast b=(B) is not allowed”);
}
         else {
Console.WriteLine(“Cast b=(B) is allowed”);
}
        }
}

Using typeof
To obtain information about type in c#
    typeof(type)

Creating Custom Attributes

1) The .NET Framework allows creation of custom attributes, which can be used to store information and can be retrieved at run time.
2) This information can be related to any target element depending upon the design and the need of an application.

3) To create custom attributes, you need to:
a) Define a custom attribute.
b) Name the custom attribute.
c) Construct the custom attribute.
d) Apply the custom attribute to a target element.

4) Defining a Custom Attribute:
a) A New custom attribute class is derived from the System.Attribute system class.
b) You need to then apply the attribute target using a predefined attribute to the new custom attribute class, AttributeUsage, as shown in the following code statement:

[AttributeUsage(AttributeTargets.Class |
 AttributeTargets.Constructor |
 AttributeTargets.Field |
 AttributeTargets.Method |
 AttributeTargets.Property,
 AllowMultiple = true)]

a) The AttributeUsage attribute allows two arguments.
i)  One argument is a set of flags that indicates the target element.
ii) The other argument is a flag that indicates whether a given element might be applied with more than one such attribute. 
b)  Besides the AllowMultiple property there are other properties that can be used with the attributes. These properties are:
   i)  Inherited
   ii) ValidOn
c) The following table lists the various member names of the AttributeTargets enumerator.

Member Name
Attribute Targets
All
Elements including assembly, class, class member, delegate, enum, event, field, interface, method, module, parameter, property, or struct
Assembly
Assembly only
Class
Instances of the class
ClassMembers
Classes, structs, enums, constructors, methods, properties, fields, events, delegates, and interfaces
Constructor
Class constructors
Delegate
Delegate methods
Enum
Defined enumeration
Event
Defined events
Field
Fields
Interface
Interfaces
Method
Defined methods
Module
A single module
Parameter
Parameters of a method
Property
Properties (both get and set, if implemented)
Struct
Structs

5) Naming the Custom Attribute:
a) The normal convention is to append the word Attribute to the attribute name.
b) The compiler supports appending by allowing you to call the attribute with the shorter version of the name.

6) Constructing the Custom Attribute:
a)  Every attribute must contain at least one constructor.
b)  Positional parameters are passed through the constructor in the order declared in the constructor, as shown in the following code snippet:

public BugFixingAttribute(int BugNo, string Developer, string DateFixed)
{
this.BugNo=BugNo;
this.Developer=Developer;
}

c) Named parameters are implemented as properties, as shown in the following code snippet:

public string Remarks
{
get
  {
    return Remarks;
  }
 set
  {
   Remarks=value;
  }
}

d) It is common to create read-only properties for the positional parameters:

public int BugNo
{
  get
    {
     return BugNo;
    }
}

7) Applying the Custom Attribute:

a) The attribute can be applied by placing it immediately before its target.
b) To test the BugFixAttribute attribute for the preceding example, you can create a program for a simple class named Calculator and give it four functions.
c) You need to assign the BugFixAttribute to the target element class to record its code-maintenance history, as shown in the following code snippet:

[BugFixingAttribute(125,"Sara Levo","08/15/06", Remarks="Return object not specified")]
[BugFixingAttribute(159,"Sara Levo","08/17/06", Remarks="Data Type Mismatch")]
public class Calculator

Retrieving Metadata Using Reflection

Reflection  is the feature in C# that enables you to obtain information about a type. A Type object mirror the underlying type it represents 

Using Reflection 
Using type methods and properties, it is possible to obtain detailed information about a type at runtime. Thus reflection enables you to use code that was not available at compile time.

1.       Reflection is used in the process of obtaining type information at runtime.
2.       The classes that give access to the metadata of a running program are in the System.Reflection namespace.
3.       The System.Reflection namespace contains classes that allow programmers to obtain information about the application that is running and to dynamically add types, values, and objects to that application.
4.       Reflection is generally used for the following tasks:
5.       Viewing metadata
6.       Performing type discovery
7.       Late binding to methods and properties
8.       Reflection emit
9.       Viewing Metadata:
10.   To view metadata using reflection, the MemberInfo object of the System.Reflection namespace needs to be initialized.
11.   This object helps discover the attributes of a member and to provide access to metadata.

Performing Type Discovery:

1.       Reflection also helps to explore and examine the contents of an assembly.
2.       It helps find the types associated with a module; the methods, fields, properties, and events associated with a type, as well as the signatures of each type of methods; the interfaces supported by the type and the type's base class.
3.       Performing type discovery can also be achieved through the Object Browser window of Visual Studio .NET IDE.

Late Binding:

1.       Binding a method at runtime is called late binding.
2.       Reflection provides the flexibility of choosing an object you will bind at runtime and calling it programmatically.

Using Delegates with Events

Reflection Emit:           
1.       Reflection emit allows creation of new types at run time and further use those types to perform certain tasks.
2.       Reflection emit enables you to define new modules and new types with methods.

Summary:-
1)      Custom attributes are attributes that you create according to your requirement.
2)      The element to which you attach an attribute is called an attribute target.
3)      Reflection is used in the process of obtaining type information at run time.
4)      Reflection is generally used for the following tasks:
5)      Viewing metadata
6)      Performing type discovery
7)      Late binding to methods and properties
8)      Reflection emit

I hope that the functionality of the above attribute is clear to you now. Now you can use this code in your application. If you have further question, just drop a line below and I will try to answer you as soon as possible.

Last but not least, connect with me on Twitter , Facebook , LinkedIn and Google+ for technical updates and articles news. We won’t spam or share your email address as we respect your privacy.



No comments:

Post a Comment