<?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/"
	>

<channel>
	<title>Martijn's C# Programming Blog &#187; reflection</title>
	<atom:link href="http://www.dijksterhuis.org/tag/reflection/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Show all assemblies loaded by your C# program</title>
		<link>http://www.dijksterhuis.org/show-assemblies-loaded-program/</link>
		<comments>http://www.dijksterhuis.org/show-assemblies-loaded-program/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 07:29:15 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=721</guid>
		<description><![CDATA[Sometimes it is handy to have a quick overview of all the assemblies that your C# program has loaded. Maybe because you are trying to debug a version conflict, or because you want to distribute your application and want to get an idea of its dependencies.

To find the loaded assemblies we first need to determine [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>Sometimes it is handy to have a quick overview of all the assemblies that your C# program has loaded. Maybe because you are trying to debug a version conflict, or because you want to distribute your application and want to get an idea of its dependencies.</em></p>
<p><span id="more-721"></span></p>
<p>To find the loaded assemblies we first need to determine the current AppDomain (it is possible for your application to have more than one AppDomain, but in that case you have created the second one yourself). Each AppDomain keeps a list of Assemblies it is using and in the following example code we query it using the GetAssemblies() method.</p>
<p>By calling FullName we obtain the name, version, culture and public key ID for each assembly. </p>
<pre class="brush: c#">
using System;
using System.Text;
using System.Reflection;

namespace AssemblyListing
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain MyDomain = AppDomain.CurrentDomain;
            Assembly[] AssembliesLoaded = MyDomain.GetAssemblies();

            foreach (Assembly MyAssembly in AssembliesLoaded)
            {
                Console.WriteLine(&quot;Loaded: {0}&quot;, MyAssembly.FullName);
            }
        }
    }
}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/show-assemblies-loaded-program/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Exploring C# reflection</title>
		<link>http://www.dijksterhuis.org/exploring-reflection/</link>
		<comments>http://www.dijksterhuis.org/exploring-reflection/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 16:00:39 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Chapter]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=680</guid>
		<description><![CDATA[
In this post I look at how we can simply retrieve basic information about our own types, discover their methods and lastly how we can import a foreign assembly, inspect its contents, load a class and execute its methods. 
When C# compiles your code it not only stores the program in the assembly but the [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2009/02/horses.jpg" alt="Reflecting on our C# selves" title="Reflecting on our C# selves" width="500" height="260" class="alignnone size-full wp-image-684" /></p>
<p><em>In this post I look at how we can simply retrieve basic information about our own types, discover their methods and lastly how we can import a foreign assembly, inspect its contents, load a class and execute its methods. </p>
<p>When C# compiles your code it not only stores the program in the assembly but the complete information on each of the structures you have defined. Each class, its types, parameters and methods described into detail are all available. This might sound like stating the obvious, but until recently most compilers treated this kind of &#8220;meta&#8221; data as a waste of space and never included it into the final assembly.</em></p>
<p><span id="more-680"></span></p>
<p>Through reflection C#  offers a way of inspecting this meta information from a running program. The program reflects on itself to discover itself. It can use this to change the way it runs, or to report the results back to the user.</p>
<p>Why is this useful? If you distribute an application that accepts third plug-ins you need some kind of mechanism to inspect whether the supplied plug-in provides the correct set of methods for your code to work with. Very similar to how Visual Studio works with plug-ins.</p>
<p><strong>Type</strong></p>
<p>To be able to interact with their own code C# programs rely heavily on the <em>Type</em> class. The <em>Type</em> class can represent all C# type declarations: class types, interface types, array types, value types, enumeration types, type parameters etc. You can use it to query a type and discover what kind of contents it has.</p>
<p><em>GetType()</em> is the most common way to access C# reflection and I&#8217;ll show in the next example how you can find out the original type of an object after it has been cast down to a basic object. The<em> GetType()</em> method is inherited from object, so each C# object has access to it. As can be expected, <em>GetType()</em> returns an instance of the Type class.</p>
<p>But first have a look a simple example of how we can use <em>GetType()</em></p>
<pre class="brush: c#">
    using System;
    using System.Reflection;
    class MainClass
    {
        // This routine takes an object, which is the root of all
        // types in C#
        public static void PrintType(object Data)
        {
            Console.WriteLine(&quot;Type of Data: {0}&quot;,Data.GetType());
        }

        public static void Main(string[] args)
        {
            string msg = &quot;Hello World&quot;;
            PrintType(msg);
            int    theValue = 1024;
            PrintType(theValue);
        }
    }
</pre>
<p>This will print:</p>
<blockquote><p>Type of Data: System.String<br />
Type of Data: System.Int32
</p></blockquote>
<p>If you know that the object you were passed was really a <em>System.Int32</em> object, you can could cast it back and modify it as a regular integer. The following works but isn&#8217;t very nice:</p>
<pre class="brush: c#">
         object Test = new int();

         // This only works if the above object is an integer
         if (Test.GetType().ToString()==&quot;System.Int32&quot;)
            {
                int MyInt = (System.Int32) Test;
                MyInt = 20;
            }
</pre>
<p>A much better way of course in your own code to do the following:</p>
<pre class="brush: c#">
         object Test = new int();
         if (Test is int)
            {
                int MyInt = (int) Test;
                MyInt = 20;
            }
</pre>
<p><strong>The TypeOf operator</strong></p>
<p>The <em>typeof()</em> operator works in similar fashion at GetType but on type definitions at compile time. The <em>GetType()</em> operator works on instances of variables and is available at run-time. The benefit is that you don&#8217;t have to instantiate a class to obtain an type instance. To illustrate the difference have a look at the following:</p>
<pre class="brush: c#">
Type e = typeof(MyExampleClass);

// This is the same as:

MyClass example = new MyExampleClass();
Type t = example.GetType();
</pre>
<p><strong>Using Type to query a class methods and members</strong></p>
<p>Of course we can obtain much more information about a class than just its name. We can use the <em>GetMethods()</em> method to obtain a list of all the methods in the class, and <em>GetMembers()</em> to obtain all its member variables. Not only that, we can also call these members after we discover them.</p>
<pre class="brush: c#">
using System;
using System.Reflection;

namespace Reflection
{
    class MySecretClass
    {
        public int Z;

        public int Add(int x) { return x+1; }
        public int Sub(int x) { return x-1; }

         MySecretClass()
        {
            Z = 0;
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
         Type t = typeof(MySecretClass);

         MethodInfo[] MethodArray = t.GetMethods();
         foreach (MethodInfo Method in MethodArray)
          Console.WriteLine(&quot;Method: {0}&quot;,Method.ToString());

         MemberInfo[] MemberArray = t.GetMembers();
         foreach (MemberInfo Member in MemberArray)
          Console.WriteLine(&quot;Member: {0}&quot;,Member.ToString());

        }
    }
}
</pre>
<p><strong>Loading an external assembly</strong></p>
<p>Inspecting our own types is not nearly as adventurous as trying to decode the definitions found in a assembly you are trying to understand or validate. The following code loads the &#8220;mscorlib.dll&#8221; (which is the present in all .NET environments) and prints its name, version, culture and public key:</p>
<pre class="brush: c#">
            System.Reflection.Assembly LoadedAssembly = System.Reflection.Assembly.Load(&quot;mscorlib.dll&quot;);
            System.Console.WriteLine(LoadedAssembly.GetName());
</pre>
<p>We can query the assembly for a couple of basic variables, such as its name, location etc:</p>
<pre class="brush: c#">
            Console.WriteLine(&quot;Full Name: {0}&quot;, LoadedAssembly.FullName);
            Console.WriteLine(&quot;Location: {0}&quot;, LoadedAssembly.Location);
            Console.WriteLine(&quot;Code Base: {0}&quot;, LoadedAssembly.CodeBase);
            Console.WriteLine(&quot;Escaped Code Base: {0}&quot;, LoadedAssembly.EscapedCodeBase);
            Console.WriteLine(&quot;Loaded from GAC: {0}&quot;, LoadedAssembly.GlobalAssemblyCache);
</pre>
<p>Now the assembly is in memory we can explore it using the above introduced Type class, the GetTypes() method returns an array of all types in the assembly. The full code that queries the mscorlib.dll in detail is below:</p>
<pre class="brush: c#">
using System;
using System.Reflection;

namespace Reflection
{
    class MainClass
    {

        public static void Main(string[] args)
        {
            System.Reflection.Assembly LoadedAssembly = System.Reflection.Assembly.Load(&quot;mscorlib.dll&quot;);
            System.Console.WriteLine(LoadedAssembly.GetName());

            Console.WriteLine(&quot;Full Name: {0}&quot;, LoadedAssembly.FullName);
            Console.WriteLine(&quot;Location: {0}&quot;, LoadedAssembly.Location);
            Console.WriteLine(&quot;Code Base: {0}&quot;, LoadedAssembly.CodeBase);
            Console.WriteLine(&quot;Escaped Code Base: {0}&quot;, LoadedAssembly.EscapedCodeBase);
            Console.WriteLine(&quot;Loaded from GAC: {0}&quot;, LoadedAssembly.GlobalAssemblyCache);

            Type[] types = LoadedAssembly.GetTypes();

            foreach (Type t in types)
            {
                Console.WriteLine (&quot;Name: {0}&quot;, t.FullName);
                Console.WriteLine (&quot;Namespace: {0}&quot;, t.Namespace);
            }
        }
    }
}
</pre>
<p><strong>Calling dynamically bound assemblies at runtime</strong></p>
<p>After we have loaded an assembly we want to execute some code in it. In the above example we used the <em>mscorelib.dll</em> because it conveniently is available on all .NET systems. In the following example I show how you can create an object instance and call a named method.</p>
<p>The <em>System.DateTime</em> class is one of many stored in this dll, and we are interested in the <em>ToLongDateString</em> method. Normally we would call it in a manner similar to the below:</p>
<pre class="brush: c#">
System.DateTime myTime   = new System.DateTime(2000,1,1,12,0,0);
Console.WriteLine(&quot;Current Time: {0}&quot;,myTime.ToLongDateString());
</pre>
<p>As we have loaded <em>mscorlib</em> dynamically we need to go through some more steps to locate the method and constructor we are interested in:</p>
<pre class="brush: c#">
object myObject = LoadedAssembly.CreateInstance(&quot;System.DateTime&quot;,false,BindingFlags.ExactBinding,null,new Object[] {2000,1,1,12,0,0},null,null);
</pre>
<p>We use <em>CreateInstance</em> to create an instance of the class we require, &#8220;System.DateTime&#8221;. Just ignore the other parameters for now; the second important one is where we pass an object array containing the exact number of variables to match the correct constructor.</p>
<p>Next we need to obtain a handle to the method inside the class we want to invoke.</p>
<pre class="brush: c#">
MethodInfo m = LoadedAssembly.GetType(&quot;System.DateTime&quot;).GetMethod(&quot;ToLongDateString&quot;);
</pre>
<p>We execute the method by calling &#8220;Invoke&#8221;, passing our object and an object array of parameters (null as ToLongDateString does not take any). We need to cast the resulting object to a string.</p>
<pre class="brush: c#">string result = (string) m.Invoke(myObject,null);
Console.WriteLine(&quot;The time and date: {0}&quot;,result);
</pre>
<p>From the above it is clear that calling methods from a dynamically loaded and bound assembly is considerably more work. It does however allow you to extend your program through third party extensions, or by enabling functionality through assemblies that might not be available on all systems.</p>
<p>The full code for the final example is below:</p>
<pre class="brush: c#">
using System;
using System.Reflection;

namespace Reflection
{
        class MainClass
        {

                public static void Main(string[] args)
                {
                        System.Reflection.Assembly LoadedAssembly = System.Reflection.Assembly.Load(&quot;mscorlib.dll&quot;);
                        System.Console.WriteLine(LoadedAssembly.GetName());

                        // Doing it the statically bound way
                        System.DateTime myTime   = new System.DateTime(2000,1,1,12,0,0);
                        Console.WriteLine(&quot;Current Time: {0}&quot;,myTime.ToLongDateString());

                        // And now through an assembly loaded at runtime
                        object myObject = LoadedAssembly.CreateInstance(&quot;System.DateTime&quot;,false,BindingFlags.ExactBinding,null,new Object[] {2000,1,1,12,0,0},null,null);

                        MethodInfo m = LoadedAssembly.GetType(&quot;System.DateTime&quot;).GetMethod(&quot;ToLongDateString&quot;);
                        string result = (string) m.Invoke(myObject,null);
                        Console.WriteLine(&quot;The time and date: {0}&quot;,result);

                }
        }
}
</pre>
<p>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/mikebaird/">Mike Baird</a></p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/exploring-reflection/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
