<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>VibrantCode - Wild Ideas</title>
    <link>http://blog.andrewnurse.net/</link>
    <description>Oooh...pretty code</description>
    <language>en-us</language>
    <copyright>Andrew Nurse</copyright>
    <lastBuildDate>Fri, 30 Jan 2009 07:45:51 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.0.7226.0</generator>
    <managingEditor>andrew@andrewnurse.net</managingEditor>
    <webMaster>andrew@andrewnurse.net</webMaster>
    <item>
      <trackback:ping>http://blog.andrewnurse.net/Trackback.aspx?guid=c585caa9-c80a-48db-af4c-78ba85e07132</trackback:ping>
      <pingback:server>http://blog.andrewnurse.net/pingback.aspx</pingback:server>
      <pingback:target>http://blog.andrewnurse.net/PermaLink,guid,c585caa9-c80a-48db-af4c-78ba85e07132.aspx</pingback:target>
      <dc:creator>Andrew Nurse</dc:creator>
      <wfw:comment>http://blog.andrewnurse.net/CommentView,guid,c585caa9-c80a-48db-af4c-78ba85e07132.aspx</wfw:comment>
      <wfw:commentRss>http://blog.andrewnurse.net/SyndicationService.asmx/GetEntryCommentsRss?guid=c585caa9-c80a-48db-af4c-78ba85e07132</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
One of the most common checks I do is a simple null check on arguments being passed
in to the methods I write.  I usually create a static class called “Arg” with
the following methods (to help out):
</p>
        <pre class="csharp" name="code">public static class Arg {
    public static void NotNull(object value, string paramName) {
        if (value == null) {
            throw new ArgumentNullException(paramName);
        }
    }
    public static void NotNullOrEmpty(string value, string paramName) {
        if (String.IsNullOrEmpty(value)) {
            // ED: Error_StringArgumentNullOrEmpty is a key in my Visual Studio
            //  project's default string resources file (Properties/Resources.resx)
            throw new ArgumentException(
                String.Format(CultureInfo.CurrentCulture, 
                              Resources.Error_StringArgumentNullOrEmpty, 
                              paramName), 
                paramName);
        }
    }
}</pre>
        <p>
Then, I can use it like this
</p>
        <pre class="csharp" name="code">public void Foo(string arg, object reallyLongArgumentName) {
    Arg.NotNullOrEmpty(arg, "arg");
    Arg.NotNull(reallyLongArgumentName, "reallyLongArgumentName");
}</pre>
        <p>
I was recently playing with <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank">lambda
expressions</a> in C# and thought of a way to make this a little cooler.  The
result is, I can rewrite the lines above like this:
</p>
        <pre class="csharp" name="code">public void Foo(string arg, object reallyLongArgumentName) {
    Arg.NotNullOrEmpty(() =&gt; arg);
    Arg.NotNull(() =&gt; reallyLongArgumentName);
}</pre>
        <p>
The first obvious advantage is that for longer argument names, its more concise. 
The second, is that I no longer have to worry about updating the strings representing
the parameter names when I rename arguments, the Visual Studio Refactoring engine
will take care of it for me.
</p>
        <p>
Obviously, this is slower than the previous method since I’m diving into the lambda
expression at runtime, but its cool.  But if I need the performance, I have a
little Regular Expression I can run in Visual Studio to convert the lambda calls back
to the string versions (and vice-versa)
</p>
        <p>
How does it work? Well, the core of the code is a static helper in the <code>Arg</code> class
</p>
        <pre class="csharp" name="code">private static string GetParameterName&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; paramExpr) {
    LambdaExpression lambda = paramExpr as LambdaExpression;
    Debug.Assert(lambda != null);
    MemberExpression paramRef = lambda.Body as MemberExpression;
    Debug.Assert(paramRef != null);

    // Get the parameter name
    string paramName = paramRef.Member.Name;
    return paramName;
}</pre>
        <p>
Lines 2-5 dive through the Expression tree to find the <code>MemberExpression</code> that
represents the parameter (i.e. "foo" in <code>() =&gt; foo</code>). Then, we pull
out the <code>MemberInfo</code> for the parameter and check the name. With that method,
the actual checker is easy:
</p>
        <pre class="csharp" name="code">public static void NotNull(Expression&lt;Func&lt;object&gt;&gt; paramExpr) {
    string paramName = GetParameterName(paramExpr);

    // Compile the lambda (to get the value)
    Func&lt;object&gt; compiledLambda = paramExpr.Compile();
    
    // Run the contract check
    NotNull(compiledLambda(), paramName);
}</pre>
        <p>
Line 2 extracts the parameter name. Line 5 compiles the lambda into an actual function
that will return the value of the parameter. Finally, Line 8 uses the value and the
parameter name to call my original <code>object/string</code> version. The code for <code>NotNullOrEmpty</code> is
nearly identical.
</p>
        <p>
Anyway, if you're concerned about performance, stick to the overloads which take the
parameter name directly. I’ve attached the code as a TXT file, just rename to C#,
change the namespace as appropriate and enjoy
</p>
        <a href="http://blog.andrewnurse.net/content/binary/Arg.txt">Arg.txt (3.93 KB)</a>
        <img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=c585caa9-c80a-48db-af4c-78ba85e07132" />
      </body>
      <title>Wild Ideas &amp;ndash; Using lambdas to check arguments in C#</title>
      <guid isPermaLink="false">http://blog.andrewnurse.net/PermaLink,guid,c585caa9-c80a-48db-af4c-78ba85e07132.aspx</guid>
      <link>http://blog.andrewnurse.net/2009/01/30/WildIdeasNdashUsingLambdasToCheckArgumentsInC.aspx</link>
      <pubDate>Fri, 30 Jan 2009 07:45:51 GMT</pubDate>
      <description>&lt;p&gt;
One of the most common checks I do is a simple null check on arguments being passed
in to the methods I write.&amp;nbsp; I usually create a static class called “Arg” with
the following methods (to help out):
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;public static class Arg {
    public static void NotNull(object value, string paramName) {
        if (value == null) {
            throw new ArgumentNullException(paramName);
        }
    }
    public static void NotNullOrEmpty(string value, string paramName) {
        if (String.IsNullOrEmpty(value)) {
            // ED: Error_StringArgumentNullOrEmpty is a key in my Visual Studio
            //  project's default string resources file (Properties/Resources.resx)
            throw new ArgumentException(
                String.Format(CultureInfo.CurrentCulture, 
                              Resources.Error_StringArgumentNullOrEmpty, 
                              paramName), 
                paramName);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;
Then, I can use it like this
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;public void Foo(string arg, object reallyLongArgumentName) {
    Arg.NotNullOrEmpty(arg, "arg");
    Arg.NotNull(reallyLongArgumentName, "reallyLongArgumentName");
}&lt;/pre&gt;
&lt;p&gt;
I was recently playing with &lt;a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank"&gt;lambda
expressions&lt;/a&gt; in C# and thought of a way to make this a little cooler.&amp;nbsp; The
result is, I can rewrite the lines above like this:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;public void Foo(string arg, object reallyLongArgumentName) {
    Arg.NotNullOrEmpty(() =&amp;gt; arg);
    Arg.NotNull(() =&amp;gt; reallyLongArgumentName);
}&lt;/pre&gt;
&lt;p&gt;
The first obvious advantage is that for longer argument names, its more concise.&amp;nbsp;
The second, is that I no longer have to worry about updating the strings representing
the parameter names when I rename arguments, the Visual Studio Refactoring engine
will take care of it for me.
&lt;/p&gt;
&lt;p&gt;
Obviously, this is slower than the previous method since I’m diving into the lambda
expression at runtime, but its cool.&amp;nbsp; But if I need the performance, I have a
little Regular Expression I can run in Visual Studio to convert the lambda calls back
to the string versions (and vice-versa)
&lt;/p&gt;
&lt;p&gt;
How does it work? Well, the core of the code is a static helper in the &lt;code&gt;Arg&lt;/code&gt; class
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;private static string GetParameterName&amp;lt;T&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; paramExpr) {
    LambdaExpression lambda = paramExpr as LambdaExpression;
    Debug.Assert(lambda != null);
    MemberExpression paramRef = lambda.Body as MemberExpression;
    Debug.Assert(paramRef != null);

    // Get the parameter name
    string paramName = paramRef.Member.Name;
    return paramName;
}&lt;/pre&gt;
&lt;p&gt;
Lines 2-5 dive through the Expression tree to find the &lt;code&gt;MemberExpression&lt;/code&gt; that
represents the parameter (i.e. "foo" in &lt;code&gt;() =&amp;gt; foo&lt;/code&gt;). Then, we pull
out the &lt;code&gt;MemberInfo&lt;/code&gt; for the parameter and check the name. With that method,
the actual checker is easy:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;public static void NotNull(Expression&amp;lt;Func&amp;lt;object&amp;gt;&amp;gt; paramExpr) {
    string paramName = GetParameterName(paramExpr);

    // Compile the lambda (to get the value)
    Func&amp;lt;object&amp;gt; compiledLambda = paramExpr.Compile();
    
    // Run the contract check
    NotNull(compiledLambda(), paramName);
}&lt;/pre&gt;
&lt;p&gt;
Line 2 extracts the parameter name. Line 5 compiles the lambda into an actual function
that will return the value of the parameter. Finally, Line 8 uses the value and the
parameter name to call my original &lt;code&gt;object/string&lt;/code&gt; version. The code for &lt;code&gt;NotNullOrEmpty&lt;/code&gt; is
nearly identical.
&lt;/p&gt;
&lt;p&gt;
Anyway, if you're concerned about performance, stick to the overloads which take the
parameter name directly. I’ve attached the code as a TXT file, just rename to C#,
change the namespace as appropriate and enjoy
&lt;/p&gt;
&lt;a href="http://blog.andrewnurse.net/content/binary/Arg.txt"&gt;Arg.txt (3.93 KB)&lt;/a&gt;&lt;img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=c585caa9-c80a-48db-af4c-78ba85e07132" /&gt;</description>
      <comments>http://blog.andrewnurse.net/CommentView,guid,c585caa9-c80a-48db-af4c-78ba85e07132.aspx</comments>
      <category>CMPT 376</category>
      <category>Random Stuff</category>
      <category>Tips</category>
      <category>Wild Ideas</category>
    </item>
  </channel>
</rss>