<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Arrao4u</title>
	<atom:link href="http://arrao4u.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://arrao4u.wordpress.com</link>
	<description>...a blog by Rama Rao</description>
	<lastBuildDate>Sat, 14 May 2011 06:20:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='arrao4u.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/1f9a24600514f2c8248b8f4c29be2a8f?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Arrao4u</title>
		<link>http://arrao4u.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://arrao4u.wordpress.com/osd.xml" title="Arrao4u" />
	<atom:link rel='hub' href='http://arrao4u.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Reflection</title>
		<link>http://arrao4u.wordpress.com/2011/05/08/reflection/</link>
		<comments>http://arrao4u.wordpress.com/2011/05/08/reflection/#comments</comments>
		<pubDate>Sun, 08 May 2011 10:04:39 +0000</pubDate>
		<dc:creator>arrao4u</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://arrao4u.wordpress.com/?p=490</guid>
		<description><![CDATA[Reflection: Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. In other words, reflection provides objects that encapsulate assemblies, modules and types. A program reflects on itself by extracting metadata from its assembly and using that metadata either to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=arrao4u.wordpress.com&amp;blog=10760081&amp;post=490&amp;subd=arrao4u&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Reflection: Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. In other words, reflection provides objects that encapsulate assemblies, modules and types. A program reflects on itself by extracting metadata from its assembly and using that metadata either to inform the user or to modify its own behavior. Reflection is similar to C++ RTTI (Runtime Type Information), but much broader in scope and capability. By using Reflection in C#, one is able to find out details of an object, method, and create objects and invoke methods at runtime. The <code>System.Reflection </code>namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types. When writing a C# code that uses reflection, the coder can use the typeof operator to get the object&#8217;s type or use the <code>GetType() </code>method to get the type of the current instance. Here are sample codes that demonstrate the use of reflection</p>
<h1>Reflection Examples [C#]</h1>
<p>This example shows how to dynamically load assembly, how to create object instance, how to invoke method or how to get and set property value.</p>
<h2>Create instance from assembly that is in your project References</h2>
<p>The following examples create instances of DateTime class from the System assembly.</p>
<p>[C#]</p>
<pre><strong>// create instance of class</strong> DateTime
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));</pre>
<p>[C#]</p>
<pre><strong>// create instance of</strong> DateTime, <strong>use constructor with parameters</strong> (year, month, day)
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime),
                                                       new object[] { 2008, 7, 4 });</pre>
<h2>Create instance from dynamically loaded assembly</h2>
<p>All the following examples try to access to <strong>sample class Calculator</strong> from Test.dll assembly. The calculator class can be defined like this.</p>
<p>[C#]</p>
<pre>namespace Test
{
    public class Calculator
    {
        public Calculator() { ... }
        private double _number;
        public double Number { get { ... } set { ... } }
        public void Clear() { ... }
        private void DoClear() { ... }
        public double Add(double number) { ... }
        public static double Pi { ... }
        public static double GetPi() { ... }
    }
}</pre>
<p><strong>Examples of using reflection</strong> to load the Test.dll assembly, to create instance of the Calculator class and to access its members (public/private, instance/static).</p>
<p>[C#]</p>
<pre><strong>// dynamically load assembly from file</strong> Test.dll
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");</pre>
<p>[C#]</p>
<pre><strong>// get type of class</strong> Calculator <strong>from just loaded assembly</strong>
Type calcType = testAssembly.GetType("Test.Calculator");</pre>
<p>[C#]</p>
<pre><strong>// create instance of class</strong> Calculator
object calcInstance = Activator.CreateInstance(calcType);</pre>
<p>[C#]</p>
<pre><strong>// get info about property:</strong> public double Number
PropertyInfo numberPropertyInfo = calcType.GetProperty("Number");</pre>
<p>[C#]</p>
<pre><strong>// get value of property:</strong> public double Number
double value = (double)numberPropertyInfo.GetValue(calcInstance, null);</pre>
<p>[C#]</p>
<pre><strong>// set value of property:</strong> public double Number
numberPropertyInfo.SetValue(calcInstance, 10.0, null);</pre>
<p>[C#]</p>
<pre><strong>// get info about static property:</strong> public static double Pi
PropertyInfo piPropertyInfo = calcType.GetProperty("Pi");</pre>
<p>[C#]</p>
<pre><strong>// get value of static property:</strong> public static double Pi
double piValue = (double)piPropertyInfo.GetValue(null, null);</pre>
<p>[C#]</p>
<pre><strong>// invoke public instance method:</strong> public void Clear()
calcType.InvokeMember("Clear",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
    null, calcInstance, null);</pre>
<p>[C#]</p>
<pre><strong>// invoke private instance method:</strong> private void DoClear()
calcType.InvokeMember("DoClear",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
    null, calcInstance, null);</pre>
<p>[C#]</p>
<pre><strong>// invoke public instance method:</strong> public double Add(double number)
double value = (double)calcType.InvokeMember("Add",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
    null, calcInstance, new object[] { 20.0 });</pre>
<p>[C#]</p>
<pre><strong>// invoke public static method:</strong> public static double GetPi()
double piValue = (double)calcType.InvokeMember("GetPi",
    BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public,
    null, null, null);</pre>
<p>[C#]</p>
<pre><strong>// get value of private field:</strong> private double _number
double value = (double)calcType.InvokeMember("_number",
    BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,
    null, calcInstance, null);</pre>
<h4>Example 1</h4>
<div id="premain0"> </div>
<pre>using System;
using System.Reflection;

public class MyClass
{
   public virtual int AddNumb(int numb1,int numb2)
   {
     int result = numb1 + numb2;
     return result;
   }

}

class MyMainClass
{
  public static int Main()
  {
    Console.WriteLine ("\nReflection.MethodInfo");
    // Create MyClass object
    MyClass myClassObj = new MyClass();
    // Get the Type information.
    Type myTypeObj = myClassObj.GetType();
    // Get Method Information.
    MethodInfo myMethodInfo = myTypeObj.GetMethod("AddNumb");
    object[] mParam = new object[] {5, 10};
    // Get and display the Invoke method.
    Console.Write("\nFirst method - " + myTypeObj.FullName + " returns " +
                         myMethodInfo.Invoke(myClassObj, mParam) + "\n");
    return 0;
  }
}</pre>
<p>Firstly, the code snippet below will get the <code>type </code>information:</p>
<div id="premain1"> </div>
<pre>Type myTypeObj = Type.GetType("MyClass");</pre>
<p>And <code>myTypeObj</code> will now have the required information about <code>MyClass</code>. Therefore we can now check if the class is an <code>abstract </code>class or a regular class by using either of these statements:</p>
<div id="premain2"> </div>
<pre>myTypeObj.IsAbstract</pre>
<p>or:</p>
<div id="premain3"> </div>
<pre>myTypeObj.IsClass</pre>
<p>The code snippet below will get the method&#8217;s information. And the method that we are interested in this case is <code>AddNumb</code>:</p>
<div id="premain4"> </div>
<pre>Methodinfo myMethodInfo = myTypeObj.GetMethod("AddNumb");</pre>
<p lang="cs">The following code snippet will invoke the <code>AddNumb</code> method:</p>
<div id="premain5"> </div>
<pre>myMethodInfo.Invoke(myClassObj, mParam);
//Example2: In this example, we will use the typeof keyword to obtain the
//          System.Type object for a type.

Public class MyClass2
{
  int answer;
  public MyClass2()
  {
    answer = 0;
  }

  public int AddNumb(intnumb1, intnumb2)
  {
    answer = numb1 + numb2;
    return answer;
  }
}</pre>
<p>The code snippet below gets the <code>System.Type</code> object for the <code>MyClass2 type</code>.</p>
<div id="premain6"> </div>
<pre>Type type1 = typeof(MyClass2);</pre>
<p>So we will now be able to create an instance of the <code>type1</code> object by passing the <code>type1</code> object to the <code>Activator.CreateInstance(type1)</code> method.</p>
<div id="premain7"> </div>
<pre>object obj = Activator.CreateInstance(type1);</pre>
<p>Then we can now invoke the <code>AddNumb</code> method of the <code>MyClass2</code> class by first creating an array of objects for the arguments that we would be passing to the <code>AddNumb(int, int) </code>method.</p>
<div id="premain8"> </div>
<pre>object[] mParam =newobject[] {5, 10};</pre>
<p>Finally, we would invoke the <code>AddNumb(int, int)</code> method by passing the method name <code>AddNumb</code> to <code>System.Type.InvokeMember() </code>with the appropriate arguments.</p>
<div id="premain9"> </div>
<pre>int res = (int)type1.InvokeMember("AddNumb", BindingFlags.InvokeMethod,null,
                                  obj, mParam);
//Here is the complete code:
using System;
using System.Reflection;

namespace Reflection
{
   class Class1
   {
    public int AddNumb(int numb1, int numb2)
    {
      int ans = numb1 + numb2;
      return ans;
    }

  [STAThread]
  static void Main(string[] args)
  {
     Type type1 = typeof(Class1);
     //Create an instance of the type
     object obj = Activator.CreateInstance(type1);
     object[] mParam = new object[] {5, 10};
     //invoke AddMethod, passing in two parameters
     int res = (int)type1.InvokeMember("AddNumb", BindingFlags.InvokeMethod,
                                        null, obj, mParam);
     Console.Write("Result: {0} \n", res);
   }
  }
}</pre>
<br />Filed under: <a href='http://arrao4u.wordpress.com/category/c/'>C#</a>, <a href='http://arrao4u.wordpress.com/category/c/reflection/'>Reflection</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/arrao4u.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/arrao4u.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/arrao4u.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/arrao4u.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/arrao4u.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/arrao4u.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/arrao4u.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/arrao4u.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/arrao4u.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/arrao4u.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/arrao4u.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/arrao4u.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/arrao4u.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/arrao4u.wordpress.com/490/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=arrao4u.wordpress.com&amp;blog=10760081&amp;post=490&amp;subd=arrao4u&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://arrao4u.wordpress.com/2011/05/08/reflection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bfa3566cff737936a6e4d14db71381df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">arrao4u</media:title>
		</media:content>
	</item>
	</channel>
</rss>
