<?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>Stefano Ricciardi &#187; reflection</title>
	<atom:link href="http://stefanoricciardi.com/tag/reflection/feed/" rel="self" type="application/rss+xml" />
	<link>http://stefanoricciardi.com</link>
	<description>On Software Development and Thereabouts</description>
	<lastBuildDate>Thu, 02 Sep 2010 15:01:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Generics With Type Uknown At Compile Time</title>
		<link>http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/</link>
		<comments>http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 20:32:20 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=773</guid>
		<description><![CDATA[The following is an example of a service containing both generic method calls and generic types. public interface IContainer&#60;T&#62; { IEnumerable&#60;IProperty&#60;T&#62;&#62; Properties { get; } } public interface IPropertyService { IContainer&#60;T&#62; GetProperties&#60;T&#62;(string propertyCode); } Now suppose that you don&#8217;t know the actual type of the data until runtime (possibly because the type is retrieved from [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F02%2F18%2Fgenerics-with-type-uknown-at-compile-time%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F02%2F18%2Fgenerics-with-type-uknown-at-compile-time%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>The following is an example of a service containing both generic method calls and generic types.</p>
<pre class="brush:csharp">
public interface IContainer&lt;T&gt;
{
    IEnumerable&lt;IProperty&lt;T&gt;&gt; Properties { get; }
}

public interface IPropertyService
{
    IContainer&lt;T&gt; GetProperties&lt;T&gt;(string propertyCode);
}
</pre>
<p>Now suppose that you don&#8217;t know the actual type of the data until runtime (possibly because the type is retrieved from a DB or from some other service). You need a way to interact with these generics, and <a href="http://msdn.microsoft.com/en-us/library/system.reflection.aspx">Reflection </a>can help you here.</p>
<p>Let&#8217;s assume that you have managed to get the <code>Type</code> of the data that you are handling (such as <code>string</code>, <code>decimal</code>, <code>double</code>, etc&#8230;) and that you have a concrete implementation of the <code>IPropertyService</code> (perhaps through Dependency Injection).</p>
<p>Once you have that, you can invoke the <code>GetProperty</code> method in the following way:</p>
<pre class="brush:csharp">
Type type = // ... this is the actual runtime type
IPropertyService service = // ... this is an instance of the service

Type serviceType = typeof(IPropertyService);
MethodInfo getPropertiesInfo =
    serviceType.GetMethod(&quot;GetProperties&quot;, new Type[] { typeof(string) });

if (getPropertiesInfo == null)
{
    // Uh-oh.... has the interface changed after we wrote this? Throw an exception...
}

Type[] genericArguments = { type }; // we only have one generic argument (&lt;t&gt;)
MethodInfo getPropertiesMethodInfo =
    getPropertiesInfo.MakeGenericMethod(genericArguments);

// Finally invoke the method to search for a price
var propertiesContainer =
    getPropertiesMethodInfo.Invoke(service, new object[] { &quot;price&quot; });
</pre>
<p>As you can see are quite a few steps to be performed, but at the end, through reflection, you end up with a container filled with all the objects that you have required.</p>
<p>Now assume that you want to access to the single properties contained in the IContainer. You need some way to invoke the C# property <code>Properties</code>. defined on <code>IContainer</code>. Similarly to the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx">MethodInfo</a> class, System.Reflection has a <a href="http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx">PropertyInfo </a>class that you can use to work with Properties.</p>
<p>The following solution, despite compiling fine, will not work at run-time:</p>
<pre class="brush:csharp">
PropertyInfo containerInfo = typeof(IContainer&lt;&gt;).GetProperty(&quot;Properties&quot;); // WRONG!!!
if (containerInfo == null)
{
    // the interface has changed. Throw an exception
}

var properties = containerInfo.GetValue(container, null) as IEnumerable;
</pre>
<p>If you try to run this, you will be greeted by the following exception: <em>Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.</em></p>
<p>After scratching my head for a while, I realized that I should have first created a generic type at run-time before retrieving the <code>PropertyInfo</code>:</p>
<pre class="brush:csharp">
Type containerType = typeof(IContainer&lt;&gt;).MakeGenericType(type);
PropertyInfo containerInfo = containerType.GetProperty(&quot;Properties&quot;);
if (containerInfo == null)
{
    // the interface has changed. Throw an exception
}

var properties = containerInfo.GetValue(container, null) as IEnumerable;
</pre>
<p>At this point I have a collection of <code>IProperties</code> which I can enumerate through. If needed, since the types in this collection are also generic, I need to repeat the process above until I reach a fundamental type (such as <code>string</code>, <code>double</code>, etc&#8230;).</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f02%2f18%2fgenerics-with-type-uknown-at-compile-time%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f02%2f18%2fgenerics-with-type-uknown-at-compile-time%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Generics-With-Type-Uknown-At-Compile-Time-Stefano-Ricciardis-Blog"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F02%2F18%2Fgenerics-with-type-uknown-at-compile-time%2F"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
