<?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>Finite Epiphany &#187; C#</title>
	<atom:link href="http://finite.mikeandcorinne.com/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://finite.mikeandcorinne.com</link>
	<description>Mike&#039;s thoughts on programming and tech</description>
	<lastBuildDate>Fri, 05 Mar 2010 23:28:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>An indexed foreach for .aspx Web Forms</title>
		<link>http://finite.mikeandcorinne.com/2008/03/an-indexed-foreach-for-aspx-web-forms/</link>
		<comments>http://finite.mikeandcorinne.com/2008/03/an-indexed-foreach-for-aspx-web-forms/#comments</comments>
		<pubDate>Tue, 11 Mar 2008 17:21:37 +0000</pubDate>
		<dc:creator>Mike Thomas</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[webforms]]></category>

		<guid isPermaLink="false">http://www.mikeandcorinne.com/finite/2008/03/11/an-indexed-foreach-for-aspx-web-forms/</guid>
		<description><![CDATA[ Nick blogged about why ASP.Net Repeaters Suck the other week and talked about using foreach loops in your .aspx.  I love this and have been doing it for a while &#8211; the strong typing and consice syntax is great.  However, sometimes I need format data based on odd and even rows&#8230;  &#60;table&#62; &#60;tr class='Row'&#62;&#60;td&#62;&#60;/td&#62;&#60;/tr&#62;   [...]]]></description>
			<content:encoded><![CDATA[<p> Nick blogged about why<span style="text-decoration: underline"> </span><a href="http://www.nickandgrace.com/code/archive/2008/03/03/asp.net-repeaters-suck.aspx#feedback">ASP.Net Repeaters Suck</a> the other week and talked about using foreach loops in your .aspx.  I love this and have been doing it for a while &#8211; the strong typing and consice syntax is great.  However, sometimes I need format data based on odd and even rows&#8230;</p>
<pre> &lt;table&gt;</pre>
<pre>   &lt;tr class='Row'&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;</pre>
<pre>   &lt;tr class='AltRow'&gt;...&lt;/tr&gt;</pre>
<pre>&lt;/table&gt;</pre>
<p>To accomplish this I created a helper function in the page code behind:</p>
<pre>protected void Foreach&lt;T&gt;(IEnumerable&lt;T&gt; enumerable, Proc&lt;T, int&gt; action){</pre>
<pre> int i = 0;</pre>
<pre> foreach(T t in enumerable){</pre>
<pre>    action(t, i);</pre>
<pre>  i++</pre>
<pre>}</pre>
<pre>}</pre>
<p>Then in the .aspx</p>
<pre>&lt;%Foreach(People, (person, i) =&gt; { %&gt;</pre>
<pre>  &lt;tr class='&lt;%=i%2==0 ?  "Row" : "AltRow"%&gt;'&gt;&lt;td&gt;&lt;%=person.FullName%&gt;&lt;/td&gt;&lt;/tr&gt;</pre>
<pre>&lt;%});%&gt;</pre>
<pre></pre>
<p>Just what I needed!</p>
]]></content:encoded>
			<wfw:commentRss>http://finite.mikeandcorinne.com/2008/03/an-indexed-foreach-for-aspx-web-forms/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C# 3.0 Expression Trees and Reflection.Emit</title>
		<link>http://finite.mikeandcorinne.com/2007/07/c-30-expression-trees-and-reflectionemit/</link>
		<comments>http://finite.mikeandcorinne.com/2007/07/c-30-expression-trees-and-reflectionemit/#comments</comments>
		<pubDate>Sat, 28 Jul 2007 04:18:44 +0000</pubDate>
		<dc:creator>Mike Thomas</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 3.0]]></category>

		<guid isPermaLink="false">http://www.mikeandcorinne.com/code/?p=6</guid>
		<description><![CDATA[C# 3.0 brings many enhancements to the C# language such as implicitly typed local variables, extension methods, lambda expressions, query expressions and expression trees (see the spec for details). Expression trees are one aspect of the language which have yet to receive the attention that they deserve. This is both surprising and expected. Surprising because [...]]]></description>
			<content:encoded><![CDATA[<p>C# 3.0 brings many enhancements to the C# language such as implicitly typed local variables, extension methods, lambda expressions, query expressions and expression trees (see the <a href="http://msdn2.microsoft.com/en-us/library/ms364047(vs.80).aspx">spec</a> for details).  Expression trees are one aspect of the language which have yet to receive the attention that they deserve.  This is both surprising and expected.  Surprising because expression trees may be one of the most powerful new features of C#.  Expected because they are the hardest to understand.</p>
<p>Here is an example.  Sometimes you need to be able to access properties on objects that you do not know the name of at compile time.  A common way of doing this is to have one class that generates delegates which are good for getting a given property from a given target type.  Like so</p>
<pre lang="csharp">   public delegate object Getter(object target);

   public interface IAccessorGenerator{
	Getter GetGetter(Type targetType, string propertyName);
   }</pre>
<p>Once we have this interface defined, we can use it like this:</p>
<pre lang="csharp">   IAccessorGenerator generator = IoC.Resolve<iaccessorgenerator>();
   Getter getPersonName = generator.GetGetter(typeof(Person), "Name");
   Person me = new Person("Mike Thomas");
   string myName = getPersonName(me);
</iaccessorgenerator></pre>
<p>Obviously, this is a poor use since the property name is know at compile time, but it will suffice.</p>
<p>Using C# 2.0 our IAccessorGenerator can be implemented in a couple ways.  First, we could use normal reflection:</p>
<pre lang="csharp">   public class ReflectingAccessorGenerator : IAccessorGenerator {
        public Getter GetGetter(Type targetType, string propertyName) {
            MethodInfo getMethod = targetType.GetProperty(propertyName).GetGetMethod();
            return delegate(object target) {
                return getMethod.Invoke(target, new object[] { });
            };
        }
    }</pre>
<p>This method is clean, easy to understand and very slow.</p>
<p>Another way to implement this method is using the powerful Reflection.Emit.  Reflection.Emit allows IL code to be generated and executed at runtime.</p>
<pre lang="csharp">    public class EmitAccessorGenerator : IAccessorGenerator{

        private static string GetRandomMethodName() {
            return Guid.NewGuid().ToString();
        }

        public Getter GetGetter(Type targetType, string propertyName)
        {
            //Get the "get" method on the target type
            MethodInfo targetGetMethod = targetType.GetProperty(propertyName).GetGetMethod();

            DynamicMethod getMethod = new DynamicMethod(
                GetRandomMethodName(),
                typeof(object),
                new Type[] { typeof(object) },
                targetType.Module);

            ILGenerator getIL = getMethod.GetILGenerator();
            getIL.Emit(OpCodes.Ldarg_0);

            if (targetType.IsValueType)
            {
                LocalBuilder lb = getIL.DeclareLocal(targetType);
                getIL.Emit(OpCodes.Unbox_Any, targetType);
                getIL.Emit(OpCodes.Stloc_0);
                getIL.Emit(OpCodes.Ldloca_S, lb);
            }
            else
            {
                getIL.Emit(OpCodes.Castclass, targetType);
            }

            if (targetGetMethod.IsVirtual)
            {
                getIL.Emit(OpCodes.Callvirt, targetGetMethod);
            }
            else
            {
                getIL.Emit(OpCodes.Call, targetGetMethod);
            }

            if (targetGetMethod.ReturnType.IsValueType)
            {
                getIL.Emit(OpCodes.Box, targetGetMethod.ReturnType);
            }

            getIL.Emit(OpCodes.Ret);

            return (Getter)getMethod.CreateDelegate(typeof(Getter));
        }
    }</pre>
<p>This method is much faster, but can is harder to understand and debug.</p>
<p>C# 3.0 allows for another option.  We can build and compile the Getter function at runtime using an expression tree.  This gives us syntax that is almost as clear as the syntax from the ReflectingAccessorGenerator that runs just as fast as the EmitAccessorGenerator:</p>
<pre lang="csharp">    public class ExpressionAccessorGenerator : IAcessorGenerator {
        public delegate object Getter(object target);

        public Getter GetGetter(Type type, string property) {
            PropertyInfo info = type.GetProperty(property);

            ParameterExpression target = Expression.Parameter(typeof(object), "target");

            Expression<getter> getter =
                Expression.Lambda<getter>(
                    Expression.Convert(
                        Expression.MakeMemberAccess(
                            Expression.Convert(target, type),
                            info
                        ),
                        typeof(object)
                    ),
                    target
                );

            return (Getter)getter.Compile();
        }
    }
</getter></getter></pre>
<p>This method is not as simple as the reflecting method, but it is still quite clear and vastly easier to debug than Reflection.Emit.</p>
<p>This is a fairly simple and contrived example, but I think that it is enough to hint at the power that lies in Expression Trees.  <a href="http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees">Some have compared the power of Expression Trees to that of Lisp</a>.  <a href="http://blogs.msdn.com/jomo_fisher/archive/2007/03/28/fast-switching-with-linq.aspx">Someone else shows how to create extremely fast switch statement</a> (I think this is an amazing example).  I am excited to see what new and powerful things that developers find to use this for!</p>
]]></content:encoded>
			<wfw:commentRss>http://finite.mikeandcorinne.com/2007/07/c-30-expression-trees-and-reflectionemit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
