<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://bloggingabout.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Search results matching tags 'C#' and 'reflection'</title><link>http://bloggingabout.net/search/SearchResults.aspx?a=1&amp;o=DateDescending&amp;tag=C%23,reflection&amp;orTags=0</link><description>Search results matching tags 'C#' and 'reflection'</description><dc:language>en-US</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><item><title>ConstructorInfo.Invoke over Activator.CreateInstance</title><link>http://bloggingabout.net/blogs/vagif/archive/2011/04/18/constructorinfo-invoke-over-activator-createinstance.aspx</link><pubDate>Mon, 18 Apr 2011 12:58:31 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:485597</guid><dc:creator>VagifAbilov</dc:creator><description>&lt;p&gt;About a year ago &lt;a href="http://bloggingabout.net/blogs/vagif/archive/2010/04/02/don-t-use-activator-createinstance-or-constructorinfo-invoke-use-compiled-lambda-expressions.aspx"&gt;I blogged about different methods of object instantiation&lt;/a&gt; and that compiled lambda expressions should be preferred in case same type is instantiated frequently and instantiation performance is critical. However, on many occasions dealing with expression compilation is not worth it, and creating an instance using reflection is simple and usually good enough. Then Activator.CreateInstance seems to be a default choice for such operations. What can be simpler than this call?&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;var instance = Activator.CreateInstance&amp;lt;SomeType&amp;gt;();&lt;/pre&gt;

&lt;p&gt;The problem with this approach is its false sense of simplicity: it gives an impression that the instance will be created without any additional information, for example initialization parameters.&lt;/p&gt;

&lt;p&gt;To prove how misleading such simplicity can be you just need to try creating an instance of a string:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;var instance = Activator.CreateInstance&amp;lt;string&amp;gt;();&lt;/pre&gt;

&lt;p&gt;The line above causes MissingMethodException with message “No parameterless constructor defined for this object”. And of course, System.String does not have a default constructor.&lt;/p&gt;

&lt;p&gt;So what to do? We can of course say that if a class does not have default constructor, then instantiating it in such way is a bad idea, and those classes are just not intended to be used with code trying to create class instances in such manner. However, I bet that more often than not the semantics behind the code “Activator.CreateInstance&amp;lt;T&amp;gt;” is “give me some instance of T, I don’t care about how you create it”. Under such conditions invoking an arbitrary class constructor is preferred over dealing with MissingMethodException. So why not using ConstructorInfo.Invoke then?&lt;/p&gt;

&lt;p&gt;Of course, once you settle for ConstructorInfo, you have to decide what constructor overload to use. But this is not really different from choosing parameterless overload of Activator.CreateInstance. In many cases you don’t choose default constructor because this the state of the object you need – you choose it because you don’t care about the state and thus would like to run the simplest form of creation. Applying the same logic to classes without default constructor we can choose a constructor overload with fewest number of parameters:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;var constructor = typeof(T).GetConstructors().OrderBy(c =&amp;gt; c.GetParameters().Length).FirstOrDefault();
if (constructor == null)
    throw new MissingMethodException(&amp;quot;No public constructor defined for this object&amp;quot;);
var instance = constructor.Invoke(new object[constructor.GetParameters().Length]);&lt;/pre&gt;

&lt;p&gt;One area when this approach can be useful is if there is a need to create an instance of an anonymous type (I know it’s a very special need – why on earth will you want to create an instance of an anonymous type? – but I’ve come across a situation):&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;var o = new { A = &amp;quot;a&amp;quot;, B = 1 };
var constructor = o.GetType().GetConstructors()[0];
var instance = constructor.Invoke(new object[constructor.GetParameters().Length]);&lt;/pre&gt;

&lt;p&gt;Anonymous types don’t get a parameterless constructor, but there is a constructor with a number of arguments equal to the number of type’s properties. I would however use syntax GetConstructors().OrderBy(c =&amp;gt; c.GetParameters().Length).FirstOrDefault() that can be applied in general case.&lt;/p&gt;</description></item><item><title>.NET 4.0 and NotSupportedException complaining about dynamic assemblies</title><link>http://bloggingabout.net/blogs/vagif/archive/2010/07/02/net-4-0-and-notsupportedexception-complaining-about-dynamic-assemblies.aspx</link><pubDate>Fri, 02 Jul 2010 12:16:16 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:483675</guid><dc:creator>VagifAbilov</dc:creator><description>&lt;p&gt;If you search for “The invoked member is not supported in a dynamic assembly” error message, you will get plenty of results. Some of them related to code that worked in .NET 2.0 and 3.x but suddenly stopped working in .NET 4.0. What may be surprising is that this error comes from the places that have nothing to do with dynamic assemblies. In fact, they are not created in application code.&lt;/p&gt;  &lt;p&gt;Here’s an example of the code that can break:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    var assemblies = from Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()
                              where !(assembly is System.Reflection.Emit.AssemblyBuilder) &amp;amp;&amp;amp;
                              !assembly.GlobalAssemblyCache &amp;amp;&amp;amp;
                              assembly.CodeBase != Assembly.GetExecutingAssembly().CodeBase
                              select assembly;

    foreach (var assembly in assemblies)
    {
        // rest of the code is skipped
    }
}&lt;/pre&gt;

&lt;p&gt;What&amp;#39;s wrong with this code when it comes to dynamic assemblies? Nothing as long as it&amp;#39;s running in CLR prior to .NET 4.0. Apparently the check &lt;strong&gt;assembly is System.Reflection.Emit.AssemblyBuilder&lt;/strong&gt; is no longer enough if you want to detect dynamic assembly under CLR 4.0. There may be dynamic assemblies that pass this test and System.NotSupportedException will be thrown on attempt to call CodeBase property on them, since they CodeBase doesn’t make sense for a dynamic assembly.&lt;/p&gt;

&lt;p&gt;However, one additional check helps: a check for assembly full name mathcing &lt;strong&gt;System.Reflection.Emit.InternalAssemblyBuilder&lt;/strong&gt;. So the code above should be rewritten in the following way:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    var assemblies = from Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()
                              where !(assembly is System.Reflection.Emit.AssemblyBuilder) &amp;amp;&amp;amp;
                              assembly.GetType().FullName != &amp;quot;System.Reflection.Emit.InternalAssemblyBuilder&amp;quot; &amp;amp;&amp;amp;
                              !assembly.GlobalAssemblyCache &amp;amp;&amp;amp;
                              assembly.CodeBase != Assembly.GetExecutingAssembly().CodeBase
                              select assembly;

    foreach (var assembly in assemblies)
    {
        // rest of the code is skipped
    }
}&lt;/pre&gt;</description></item><item><title>Don’t use Activator.CreateInstance or ConstructorInfo.Invoke, use compiled lambda expressions</title><link>http://bloggingabout.net/blogs/vagif/archive/2010/04/02/don-t-use-activator-createinstance-or-constructorinfo-invoke-use-compiled-lambda-expressions.aspx</link><pubDate>Fri, 02 Apr 2010 15:43:00 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:483053</guid><dc:creator>VagifAbilov</dc:creator><description>&lt;p&gt;For a long time I’ve been under impression that rule engine that comes with Microsoft Windows Workflow Foundation is slow, very slow. We used it to execute some of our business rules, and soon found out that rule processing slows down application execution. What was strange is that the rules were really simple and it was hard to believe that an industry-strength rule engine uses so long time on processing them.&lt;/p&gt;  &lt;p&gt;Eventually I ran a profiler, and it immediately showed where the time was spent. In fact it was not the actual rule validation but preparation for it: instantiation of the WF rule parser. The parser class is not public, so we used a trick to obtain its instance: retrieved its non-public constructor information via reflection and then called Invoke.&lt;/p&gt;  &lt;p&gt;This was sloooow. So slow that we noticed it in our integration tests. What made it noticeable is that after we converted some of our business rules to use WF rule engine, we were encouraged by results and move more rules to use the same techinque. In the end rule validation was called many times during a single business operation, and performance deteriorated.&lt;/p&gt;  &lt;p&gt;My first approach to this issue was to cache validated rules, and it worked. The total time to execute integration tests was reduced by 50%. However, I was not quite happy with the situation: we have various places where objects are instantiated using reflection, caching is not always possible and in general complicates component design. Recently I reviewed the code of &lt;a href="http://structuremap.github.com/structuremap/index.html" target="_blank"&gt;StructureMap&lt;/a&gt; (I like reading good code), and remembered that it no longer used reflection and instead instantiated dependencies using compiled lambda expressions.&lt;/p&gt;  &lt;p&gt;Roger Alsing in &lt;a href="http://rogeralsing.com/2008/02/28/linq-expressions-creating-objects/" target="_blank"&gt;this post&lt;/a&gt; presented a generic method that can be used as a replacement for constructor method invocation. The essence of the method is in it’s last three lines:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;// Make a NewExpression that calls the ctor with the args we just created
NewExpression newExp = Expression.New(ctor, argsExp);                  

// Create a lambda with the New expression as body and our param object[] as arg
LambdaExpression lambda = Expression.Lambda(typeof(ObjectActivator), newExp, param);              

// Compile it
ObjectActivator compiled = (ObjectActivator)lambda.Compile();&lt;/pre&gt;

&lt;p&gt;Although lambda expressions are part of LINQ (and you have to import System.Linq.Expressions namespace to manage them), as we can see from this example, they can be very useful to solve core language tasks, such as object instantiation.&lt;/p&gt;

&lt;p&gt;But what is the gain? The gain is huge bringing the performance close to the speed of native IL code. I wrote a few tests to measure performance of object creation in different scenarios: by calling ‘new’ constructor, Activator.CreateInstance, ConstructorInfo.Invoke and using compiled lambda expression. Here are the results:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;DefaultConstructor_Activator: (0,20 ms per 1000 calls)
DefaultConstructor_CompiledExpression: (0,04 ms per 1000 calls)
DefaultConstructor_Invoke: (1,07 ms per 1000 calls)
DefaultConstructor_New: (0,02 ms per 1000 calls)
DefaultConstructor_NotCompiledExpression: (169,00 ms per 1000 calls)
NonDefaultConstructor_Activator: (3,39 ms per 1000 calls)
NonDefaultConstructor_CompiledExpression: (0,07 ms per 1000 calls)
NonDefaultConstructor_Invoke: (1,57 ms per 1000 calls)
NonDefaultConstructor_New: (0,02 ms per 1000 calls)
NonDefaultConstructor_NotCompiledExpression: (293,00 ms per 1000 calls)&lt;/pre&gt;

&lt;p&gt;Results says it all, especially when arranged in a graph.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/3022.Chart_5F00_4A95396D.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="Chart" border="0" alt="Chart" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/7217.Chart_5F00_thumb_5F00_55552173.png" width="533" height="526" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;I removed from the graph the results for not compiled lambda expressions, because they make other figures insignificant. But it is important to remember that compilation should be performed only once, so the code should be carefully reviewed to avoid occasional recompilcation of lambdas.&lt;/p&gt;

&lt;p&gt;P.S. The title of this blog post may look provocative, and of course I don’t really mean somebody should completely stop using Activator.CreateInstance. Compilation of labmda expressions is expensive enough to limit it’s practical use. But there are certain use cases (like IoC frameworks) when it gives clear performance advantage.&lt;/p&gt;</description></item></channel></rss>