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

<channel>
	<title>void Nish(char* szBlog);</title>
	<atom:link href="http://blog.voidnish.com/wp-rss2.php" rel="self" type="application/rss+xml" />
	<link>http://blog.voidnish.com</link>
	<description>Nish's thoughts on MFC, C++/CLI and .NET</description>
	<pubDate>Sat, 27 Jun 2009 16:31:12 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>A boolean lock using IDisposable</title>
		<link>http://blog.voidnish.com/?p=192</link>
		<comments>http://blog.voidnish.com/?p=192#comments</comments>
		<pubDate>Tue, 23 Jun 2009 16:28:36 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=192</guid>
		<description><![CDATA[While there are more complex and functional lock mechanisms, I wanted a very simple lock that would tell me if an operation was locked or not. Normally I would just have a flag that&#8217;d be true or false, but I found that it was not always easy to remember to set the flag on or [...]]]></description>
			<content:encoded><![CDATA[<p>While there are more complex and functional lock mechanisms, I wanted a very simple lock that would tell me if an operation was locked or not. Normally I would just have a flag that&#8217;d be <code>true </code>or <code>false</code>, but I found that it was not always easy to remember to set the flag on or off, and also to make sure the flag was set at the right place. So I came up with this class :</p>
<pre><span class="keyword">public</span> <span class="keyword">class</span> BooleanLock
{
    <span class="keyword">public</span> <span class="keyword">bool</span> Locked { <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; }

    <span class="keyword">public</span> <span class="keyword">class</span> BlockLock : IDisposable
    {
        <span class="keyword">private</span> BooleanLock _parent;

        <span class="keyword">public</span> BlockLock(BooleanLock parent)
        {
            _parent = parent;
            _parent.Locked = <span class="keyword">true</span>;
        }

        #region IDisposable Members

        <span class="keyword">public</span> <span class="keyword">void</span> Dispose()
        {
            _parent.Locked = <span class="keyword">false</span>;
        }

        #endregion
    }

    <span class="keyword">public</span> BlockLock Lock()
    {
        <span class="keyword">return</span> <span class="keyword">new</span> BlockLock(<span class="keyword">this</span>);
    }
}</pre>
<p>Now I could use it this way :</p>
<pre><span class="comment">// Declare a field as a lock</span>
<span class="keyword">private</span> BooleanLock _myUpdateLock = <span class="keyword">new</span> BooleanLock();

<span class="comment">// Check for lock</span>
<span class="keyword">private</span> <span class="keyword">void</span> UpdateSomeProperty(<span class="keyword">bool</span> reset)
{
    <span class="keyword">if</span> (_myUpdateLock.Locked)
        <span class="keyword">return</span>;

    <span class="comment">// . . .</span></pre>
<p>And here&#8217;s where the lock is set :</p>
<pre><span class="comment">// Part of the function is not re-entrant, so we use a lock there</span>
<span class="keyword">private</span> <span class="keyword">void</span> OnSomePropertyChanged()
{
    <span class="keyword">if</span> (some-condition)
    {
        <span class="keyword">using</span> (_myUpdateLock.Lock())
        {
            <span class="comment">// do non-re-entrant stuff</span>
        } &lt;-- <span class="keyword">lock</span> <span class="keyword">is</span> released here automatically</pre>
<p>The big advantage here is that the C# compiler&#8217;s <code>using</code>-block behavior handles complex <code>try</code>-<code>catch </code>scenarios that I would otherwise have had to implement on my own.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=192</wfw:commentRss>
		</item>
		<item>
		<title>Checking for Design-Mode</title>
		<link>http://blog.voidnish.com/?p=191</link>
		<comments>http://blog.voidnish.com/?p=191#comments</comments>
		<pubDate>Sun, 21 Jun 2009 15:15:15 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=191</guid>
		<description><![CDATA[The DesignMode property does not always return the correct value, specially for nested controls or for child controls instantiated in their parent control&#8217;s constructors. One workaround is to check for LicenseManager.UsageMode and see if it&#8217;s equal to LicenseUsageMode.Runtime, but even that won&#8217;t work all the time. It will always return Runtime from event handlers and [...]]]></description>
			<content:encoded><![CDATA[<p>The <code>DesignMode</code> property does not always return the correct value, specially for nested controls or for child controls instantiated in their parent control&#8217;s constructors. One workaround is to check for <code>LicenseManager.UsageMode</code> and see if it&#8217;s equal to <code>LicenseUsageMode.Runtime</code>, but even that won&#8217;t work all the time. It will always return <code>Runtime</code> from event handlers and worker threads, so a more guaranteed approach is to see if the current process-name is <em>devenv</em>. Of course that&#8217;s a slightly heavier call so we should still check for <code>LicenseManager.UsageMode</code> first, and only check the process-name if we have to.</p>
<pre><span class="keyword">bool</span> isDesignMode = LicenseManager.UsageMode == LicenseUsageMode.Designtime
  || Process.GetCurrentProcess().ProcessName.ToLowerInvariant().Contains(<span class="string">"devenv"</span>);</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=191</wfw:commentRss>
		</item>
		<item>
		<title>Exposing List&#60;T&#62; vs IList&#60;T&#62;</title>
		<link>http://blog.voidnish.com/?p=190</link>
		<comments>http://blog.voidnish.com/?p=190#comments</comments>
		<pubDate>Sun, 14 Jun 2009 11:15:25 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=190</guid>
		<description><![CDATA[Unless you specifically want to expose a List&#60;T&#62; via a public interface (either as a return type or as a method argument), it&#8217;s a better idea to expose an IList&#60;T&#62;, ICollection&#60;T&#62;, or even an  IEnumerable&#60;T&#62; depending on your needs. Recently I had to implement a generic list class that implemented property notifications and for [...]]]></description>
			<content:encoded><![CDATA[<p>Unless you specifically want to expose a <code>List&lt;T&gt;</code> via a public interface (either as a return type or as a method argument), it&#8217;s a better idea to expose an <code>IList&lt;T&gt;</code>, <code>ICollection&lt;T&gt;</code>, or even an  <code>IEnumerable&lt;T&gt;</code> depending on your needs. Recently I had to implement a generic list class that implemented property notifications and for this purpose I wrote a collection class that implemented <code>IList&lt;T&gt;</code> which by the way implements both <code>ICollection&lt;T&gt;</code> and <code>IEnumerable&lt;T&gt;</code>. I thought it&#8217;d be a simple matter to change members of certain types that used a <code>List&lt;T&gt;</code> to use this new collection class. </p>
<p>Unfortunately, I found that there were several methods in containing classes as well as calling classes that expected <code>List&lt;T&gt;</code> objects (even though the callers only used <code>IList&lt;T&gt;</code> or <code>ICollection&lt;T&gt;</code> members). Eventually I ended up having to change calling code and utility helper methods to use an <code>IList&lt;T&gt;</code> or <code>ICollection&lt;T&gt;</code> as appropriate. (Note that exposing the notification list was out of the question as it was not accessible to some of the callers and it is not good practice anyway).</p>
<p>In some cases the code used <code>List&lt;T&gt;</code> specific methods like <code>Find</code>, but if you have LINQ available then you don&#8217;t need to use the <code>List&lt;T&gt;</code> methods since you have alternate and usually more useful extension methods that you can use. I suppose I am over-specializing here by talking about <code>List&lt;T&gt;</code> in particular because it&#8217;s probably a good general practice to always expose the least derived class that you really need to.</p>
<p>Note that if you really need to expose a solid class without letting the users change the collection, then using <code>ReadOnlyCollection&lt;T&gt;</code> would be the correct approach compared to directly exposing the <code>List&lt;T&gt;</code> or <code>Collection&lt;T&gt;</code> object or their related interfaces like <code>IList&lt;T&gt;</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=190</wfw:commentRss>
		</item>
		<item>
		<title>C# 4.0 and variant generic delegates</title>
		<link>http://blog.voidnish.com/?p=189</link>
		<comments>http://blog.voidnish.com/?p=189#comments</comments>
		<pubDate>Fri, 29 May 2009 19:03:04 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=189</guid>
		<description><![CDATA[Continuing on from my previous blog entry, in this entry I will talk about variant generic delegates. Just as with generic interfaces, generic delegates can use out and in to specify covariant and contravariant parameters respectively. And the MSIL equivalents are the + and - symbols.
Here are three variant generic delegate declarations:
delegate T CovariantDelegate&#60;out T&#62;();
delegate [...]]]></description>
			<content:encoded><![CDATA[<p>Continuing on from my previous blog entry, in this entry I will talk about variant generic delegates. Just as with generic interfaces, generic delegates can use <code>out </code>and <code>in </code>to specify covariant and contravariant parameters respectively. And the MSIL equivalents are the <code>+ </code>and <code>-</code> symbols.</p>
<p>Here are three variant generic delegate declarations:</p>
<pre><span class="keyword">delegate</span> T CovariantDelegate&lt;<span class="keyword">out</span> T&gt;();
<span class="keyword">delegate</span> <span class="keyword">void</span> ContraVariantDelegate&lt;<span class="keyword">in</span> T&gt;(T t);
<span class="keyword">delegate</span> T1 ContraAndCovariantDelegate&lt;<span class="keyword">out</span> T1, <span class="keyword">in</span> T2&gt;(T2 t2);</pre>
<p>The rules are the same as with generic interfaces. The covariant delegate can only use the generic parameter as a return type, while the contravariant delegate can only use it as a delegate argument and not as a return type. The third delegate is both covariant and contravariant but with respect to two separate parameters. And here&#8217;s how these delegates can be used:</p>
<pre><span class="keyword">static</span> Derived SomeFunc()
{
    <span class="keyword">return</span> <span class="keyword">new</span> Derived();
}

<span class="keyword">static</span> <span class="keyword">void</span> SomeOtherFunc(Base b)
{
}

<span class="keyword">static</span> Derived AnotherFunc(Base b)
{
    <span class="keyword">return</span> <span class="keyword">new</span> Derived();
}

<span class="keyword">private</span> <span class="keyword">void</span> DoDelegates()
{
    CovariantDelegate&lt;Base&gt; covariantDeleg = SomeFunc; &lt;--(#<span class="number">1</span>)

    ContraVariantDelegate&lt;Derived&gt; contraDeleg = SomeOtherFunc; &lt;--(#<span class="number">2</span>)

    ContraAndCovariantDelegate&lt;Base, Derived&gt; contraCovarDeleg = AnotherFunc; &lt;--(#<span class="number">3</span>)
}</pre>
<p>(#1) : Covariance at play here. Even though <code>SomeFunc </code>returns a <code>Derived </code>type, we use it to instantiate a delegate that expects a <code>Base </code>type.</p>
<p>(#2) : Contravariance here. The delegate expects a <code>Derived </code>argument, but we pass it a method that takes a <code>Base </code>argument.</p>
<p>(#3) : This is essentially a mix of (#1) and (#2).</p>
<p>Here&#8217;s a more realistic use of variance in generic delegates:</p>
<pre><span class="keyword">class</span> Item
{
    . . .

    <span class="keyword">public</span> <span class="keyword">int</span> Code { <span class="keyword">get</span>; <span class="keyword">set</span>; }
}

<span class="keyword">class</span> Book : Item
{
    <span class="keyword">public</span> <span class="keyword">string</span> Title { <span class="keyword">get</span>; <span class="keyword">set</span>; }
}

<span class="keyword">class</span> DVD : Item
{
    <span class="keyword">public</span> <span class="keyword">string</span> Description { <span class="keyword">get</span>; <span class="keyword">set</span>; }

    <span class="keyword">public</span> <span class="keyword">int</span> Duration { <span class="keyword">get</span>; <span class="keyword">set</span>; }
}

Item FindItem(<span class="keyword">string</span> searchText, Func&lt;<span class="keyword">string</span>, Item&gt; findFunc)
{
    <span class="keyword">return</span> findFunc(searchText);
}</pre>
<p>Notice how the <code>FindItem </code>method&#8217;s second parameter is a <code>Func&lt;&gt;</code> object that itself takes a <code>string</code> and returns an <code>Item</code>. <code>Func</code>&#8217;s return type parameter is covariant, and that&#8217;s what we can take advantage of. The code below shows two methods, one that searches for a book, and the other that searches for a DVD.</p>
<pre><span class="keyword">static</span> List&lt;Book&gt; books = &lt; . . . &gt;

<span class="keyword">static</span> Book FindBook(<span class="keyword">string</span> searchText)
{
    <span class="keyword">return</span> books.FirstOrDefault(book =&gt; book.Title == searchText);
}

<span class="keyword">static</span> List&lt;DVD&gt; dvds = &lt; . . . &gt;

<span class="keyword">static</span> DVD FindDVD(<span class="keyword">string</span> searchText)
{
    <span class="keyword">return</span> dvds.FirstOrDefault(dvd =&gt;
        dvd.Description.StartsWith(searchText)
        || searchText.Contains(dvd.Duration.ToString()));
}</pre>
<p>The following code shows how to call <code>FindItem </code>using a delegate of our choice.</p>
<pre>Item book = FindItem(<span class="string">"C++/CLI in Action"</span>, FindBook);

Item dvd = FindItem(<span class="string">"Batman"</span>, FindDVD);</pre>
<p>In the first call, we pass a method that returns a <code>Book</code>, whereas the method signature expects a method that returns an <code>Item</code>. But since <code>Func&lt;&gt;</code>&#8217;s return parameter is covariant, this works fine. Essentially we are passing a <code>Func&lt;string, Book&gt;</code> as a <code>Func&lt;string, Item&gt;</code> argument. It&#8217;s the same for the second call too except that we have a <code>DVD </code>instead of a <code>Book</code>.</p>
<p>Now let&#8217;s see a contravariant delegate example. Consider the following method:</p>
<pre><span class="keyword">void</span> ShowItemCode&lt;T&gt;(T item, Action&lt;T&gt; showFunc)
{
    showFunc(item);
}</pre>
<p>It takes an <code>Action&lt;T&gt;</code> as the second argument which is a contravariant generic delegate. Now consider the following code:</p>
<pre><span class="keyword">static</span> <span class="keyword">void</span> ShowCode(Item item)
{
    Console.WriteLine(item.Code);
}

. . .

Book book = &lt; initialize here . . .&gt;
ShowItemCode(book, ShowCode);

DVD dvd = &lt; initialize here . . .&gt;
ShowItemCode(dvd, ShowCode);</pre>
<p>In the first case we are calling <code>ShowItemCode&lt;Book&gt;</code> which expects <code>Action&lt;Book&gt;</code> as the second argument. But we pass <code>ShowCode(Item) </code>which matches <code>Action&lt;Item&gt;</code> yet it works because <code>Action&lt;&gt;</code> is contravariant.</p>
<p>Remember how in the previous entry I had mentioned a case where a covariant parameter type can be used as the parameter type for a contravariant delegate argument? Well, here&#8217;s an example of that:</p>
<pre><span class="keyword">interface</span> ITestCovariant&lt;<span class="keyword">out</span> T&gt;
{
    <span class="comment">//void Bar(T t); &lt;-- won't compile</span>
    <span class="keyword">void</span> Foo1(Action&lt;T&gt; func);
    <span class="keyword">void</span> Foo2(Func&lt;T, <span class="keyword">bool</span>&gt; func);
}</pre>
<p>Even though <code>T</code> is a covariant parameter, we can use it as the parameter type for <code>Action&lt;&gt;</code> since <code>Action </code>is contravariant. I have also used it as the first type argument for the <code>Func&lt;&gt; </code>argument because though <code>Func&lt;&gt; </code>has a covariant return type, it&#8217;s input argument generic types are contravariant. Similarly for a contravariant interface:</p>
<pre><span class="keyword">interface</span> ITestContravariant&lt;<span class="keyword">in</span> T&gt;
{
    <span class="comment">//T Bar(); &lt;-- won't compile</span>
    Func&lt;T, <span class="keyword">bool</span>&gt; Foo1();
    Action&lt;T&gt; Foo2();
}</pre>
<p>Here, we have a contravariant parameter <code>T</code>, but we&#8217;ve indirectly used it in the return type by using it to set the contravariant parameters in the <code>Func&lt;&gt;</code> and <code>Action&lt;&gt;</code> delegates.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=189</wfw:commentRss>
		</item>
		<item>
		<title>C# 4.0 and variant generic interfaces</title>
		<link>http://blog.voidnish.com/?p=188</link>
		<comments>http://blog.voidnish.com/?p=188#comments</comments>
		<pubDate>Wed, 27 May 2009 16:16:25 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=188</guid>
		<description><![CDATA[The CLI supports variant generic parameters for interfaces as well as delegates, and C# 4.0 has added support for that. In this blog entry I&#8217;ll talk a little about variance in generic interfaces, and in a later entry I will talk about variance in delegates.
Covariance allows you to use a more derived type than what&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>The CLI supports variant generic parameters for interfaces as well as delegates, and C# 4.0 has added support for that. In this blog entry I&#8217;ll talk a little about variance in generic interfaces, and in a later entry I will talk about variance in delegates.</p>
<p>Covariance allows you to use a more derived type than what&#8217;s specified by the generic parameter, whereas contravariance allows you to use a less derived type. Generic interfaces can be covariant, contravariant, or both (though not for the same parameter). </p>
<p>Consider the following code:</p>
<pre><span class="keyword">class</span> Base
{
}

<span class="keyword">class</span> Derived : Base
{
}

<span class="keyword">interface</span> ICovariant&lt;<span class="keyword">out</span> T&gt; &lt;-- covariant parameter
{
}

<span class="keyword">class</span> Covariant&lt;T&gt; : ICovariant&lt;T&gt;
{
}

<span class="keyword">interface</span> IContraVariant&lt;<span class="keyword">in</span> T&gt; &lt;-- contravariant parameter
{
}

<span class="keyword">class</span> ContraVariant&lt;T&gt; : IContraVariant&lt;T&gt;
{
}</pre>
<p>There&#8217;s a base class and a derived class, a covariant interface, an implementation of that interface, a contravariant interface, and its implementation. In C# a covariant parameter is prefixed with <code>out</code>, and a contravariant parameter is prefixed with <code>in</code>. In MSIL the symbols <code>+</code> and <code>-</code> are used for covariance and contravariance. (Note : at the time of writing, Reflector does not recognize or show variant generic parameters, but ildasm does show it correctly).</p>
<p>Here&#8217;s some code that shows the variance in action:</p>
<pre>ICovariant&lt;Base&gt; baseCov = <span class="keyword">new</span> Covariant&lt;Base&gt;();
ICovariant&lt;Derived&gt; derivedCov = <span class="keyword">new</span> Covariant&lt;Derived&gt;();
baseCov = derivedCov; &lt;-- covariance

IContraVariant&lt;Base&gt; baseContra = <span class="keyword">new</span> ContraVariant&lt;Base&gt;();
IContraVariant&lt;Derived&gt; derivedContra = <span class="keyword">new</span> ContraVariant&lt;Derived&gt;();
derivedContra = baseContra; &lt;--contravariance</pre>
<p>In the first case, we were able to assign a more derived generic instantiation to be assigned to a less derived one. In the second case we did the exact opposite. The Base Class Library has been updated to support covariance and contravariance in various commonly used interfaces. For example, <code>IEnumerable&lt;T&gt;</code> is now a covariant interface - <code>IEnumerable&lt;out T&gt;</code>. This lets us do:</p>
<pre>IEnumerable&lt;<span class="keyword">object</span>&gt; objects = <span class="keyword">new</span> List&lt;<span class="keyword">string</span>&gt;();
IEnumerable&lt;Base&gt; baseList = <span class="keyword">new</span> List&lt;Derived&gt;();</pre>
<p>That was something you could not do prior to C# 4.0. Now you won&#8217;t have to use LINQ&#8217;s <code>Cast&lt;&gt;()</code> as often as you may doing now. There are some rules to follow when using variant generic parameters.</p>
<p>For covariant generic parameters, the generic parameter can only be a return type, it cannot be used as a method argument. It also cannot be used as a generic constraint. (Note : A contravariant delegate can be used as a method parameter that uses the generic parameter as its generic parameter type. I&#8217;ll talk about it in my entry on variant delegates)</p>
<p>For contravariant generic parameters, the rules are basically reversed. The parameter type can only be a method argument or a generic type constraint, it cannot be used as a return type. Here&#8217;s an interface that has both contravariant and covariant generic parameters. </p>
<pre><span class="keyword">interface</span> IContraAndCovariant&lt;<span class="keyword">in</span> T1, <span class="keyword">out</span> T2&gt;
{
    <span class="comment">//T1 Foo(T2 value); &lt;-- won't compile</span>

    T2 Foo(T1 <span class="keyword">value</span>);
}</pre>
<p>Here&#8217;s a more realistic example of where covariance comes in very handy:</p>
<pre><span class="keyword">class</span> Item
{
    <span class="keyword">public</span> <span class="keyword">void</span> CheckOut()
    {
        Console.WriteLine(<span class="string">"{0} checked out"</span>, Code);
    }

    <span class="keyword">public</span> <span class="keyword">int</span> Code { <span class="keyword">get</span>; <span class="keyword">set</span>; }
}

<span class="keyword">class</span> Book : Item
{
    <span class="keyword">public</span> <span class="keyword">string</span> Title { <span class="keyword">get</span>; <span class="keyword">set</span>; }
}

<span class="keyword">static</span> <span class="keyword">void</span> CheckOutItem(IEnumerable&lt;Item&gt; source, <span class="keyword">int</span> code)
{
    <span class="keyword">try</span>
    {
        source.First(item =&gt; item.Code == code).CheckOut();
    }
    <span class="keyword">catch</span> (InvalidOperationException ex)
    {
        Debug.WriteLine(ex.Message); <span class="comment">// invalid code</span>
    }
}</pre>
<p><code>CheckOutItem </code>expects an <code>IEnumerable </code>of <code>Item </code>elements, but because <code>IEnumerable&lt;T&gt;</code> is covariant, I can do this:</p>
<pre>List&lt;Book&gt; books = <span class="keyword">new</span> List&lt;Book&gt;()
{
    <span class="keyword">new</span> Book(){Code = <span class="number">99</span>, Title = <span class="string">"C++/CLI in Action"</span>},
    <span class="keyword">new</span> Book(){Code = <span class="number">101</span>, Title = <span class="string">"Ajax in Action"</span>},
    <span class="keyword">new</span> Book(){Code = <span class="number">105</span>, Title = <span class="string">"ASP.NET Ajax in Action"</span>},
};

CheckOutItem(books, <span class="number">99</span>);</pre>
<p>I have passed an <code>IEnumerable&lt;Book&gt;</code> to a method where an <code>IEnumerable&lt;Item&gt;</code> was expected. And here&#8217;s a realistic example of where contravariance can be used:</p>
<pre><span class="keyword">class</span> ItemComparer : IComparer&lt;Item&gt;
{
    <span class="keyword">public</span> <span class="keyword">int</span> Compare(Item x, Item y)
    {
        <span class="keyword">return</span> x.Code.CompareTo(y.Code);
    }
}

<span class="keyword">private</span> <span class="keyword">void</span> ContravarianceTest()
{
    List&lt;Book&gt; books = <span class="keyword">new</span> List&lt;Book&gt;()
    {
        <span class="keyword">new</span> Book(){Code = <span class="number">199</span>, Title = <span class="string">"C++/CLI in Action"</span>},
        <span class="keyword">new</span> Book(){Code = <span class="number">501</span>, Title = <span class="string">"Ajax in Action"</span>},
        <span class="keyword">new</span> Book(){Code = <span class="number">105</span>, Title = <span class="string">"ASP.NET Ajax in Action"</span>},
    };

    books.Sort(<span class="keyword">new</span> ItemComparer());
}</pre>
<p>I used the <code>List&lt;T&gt;.Sort</code> overload that takes an <code>IComparer&lt;T&gt;</code> argument which in this case would have been an <code>IComparer&lt;Book&gt;</code> but since <code>IComparer&lt;T&gt;</code> is contravariant with regard to <code>T</code>, I could pass my <code>ItemComparer </code>class which is actually an <code>IComparer&lt;Item&gt;</code>.</p>
<p>Funnily, now that it&#8217;s available it&#8217;s kind of hard to think of how people managed to go without this all these years. It&#8217;s more the sort of feature that gets a &#8220;woah, we didn&#8217;t have this before!&#8221; response from people. In a later entry I will discuss variance in delegates.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=188</wfw:commentRss>
		</item>
		<item>
		<title>Named and optional parameters in C# 4.0</title>
		<link>http://blog.voidnish.com/?p=187</link>
		<comments>http://blog.voidnish.com/?p=187#comments</comments>
		<pubDate>Tue, 26 May 2009 02:40:17 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=187</guid>
		<description><![CDATA[One commonly heard grievance about C# was how it did not support optional parameters. Well C# 4.0 not only has that, but you can also specify parameters by name.
Consider the following two examples :
public void RepeatText(string text, int count = 3)
{
    while (count-- &#62; 0)
    {
    [...]]]></description>
			<content:encoded><![CDATA[<p>One commonly heard grievance about C# was how it did not support optional parameters. Well C# 4.0 not only has that, but you can also specify parameters by name.</p>
<p>Consider the following two examples :</p>
<pre><span class="keyword">public</span> <span class="keyword">void</span> RepeatText(<span class="keyword">string</span> text, <span class="keyword">int</span> count = <span class="number">3</span>)
{
    <span class="keyword">while</span> (count-- &gt; <span class="number">0</span>)
    {
        Console.WriteLine(text);
    }

    Console.WriteLine();
}

<span class="keyword">public</span> <span class="keyword">void</span> RepeatDecoratedText(<span class="keyword">string</span> text, <span class="keyword">string</span> decoration = <span class="string">"Mr."</span>, <span class="keyword">int</span> count = <span class="number">3</span>)
{
    <span class="keyword">while</span> (count-- &gt; <span class="number">0</span>)
    {
        Console.WriteLine(<span class="string">"{0} {1}"</span>, decoration, text);
    }

    Console.WriteLine();
}</pre>
<p><code>RepeatText </code>has an optional parameter <code>count </code>with a default value of <code>3</code>, while <code>RepeatDecoratedText </code>has two optional parameters. The MSIL generated for these methods are as follows (simplified, and not exact) :</p>
<pre>.method <span class="keyword">public</span> <span class="keyword">void</span> RepeatText(string text, [opt] int32 count)
{
    .param [<span class="number">2</span>] = int32(<span class="number">3</span>)

.method <span class="keyword">public</span> <span class="keyword">void</span> RepeatDecoratedText(string text, [opt] string decoration, [opt] int32 count)
{
    .param [<span class="number">2</span>] = string('Mr.')
    .param [<span class="number">3</span>] = int32(<span class="number">3</span>)</pre>
<p><code>[opt]</code> is a parameter attribute that indicates that this parameter is optional and that the default value will be specified by <code>.param</code> entries. These methods can now be called as follows:</p>
<pre>RepeatText(<span class="string">"Nish"</span>);
RepeatText(<span class="string">"Ant"</span>, <span class="number">2</span>); </pre>
<p>The compiler generates code with the optional values filled in as needed:</p>
<pre>RepeatText(<span class="string">"Nish"</span>, <span class="number">3</span>); &lt;-- 2nd param <span class="keyword">set</span> via .param <span class="keyword">value</span>
RepeatText(<span class="string">"Ant"</span>, <span class="number">2</span>); &lt;-- No extra work needed</pre>
<p>You can also now pass an argument by name. This is particularly useful when you want to skip some optional args, but provide others.</p>
<pre>RepeatDecoratedText(<span class="string">"Nish"</span>, count: <span class="number">2</span>);
RepeatDecoratedText(count: <span class="number">2</span>, text: <span class="string">"Ant"</span>);
RepeatDecoratedText(decoration: <span class="string">"The super"</span>, count: <span class="number">2</span>, text: <span class="string">"Ant"</span>);</pre>
<p>That gets compiled as:</p>
<pre>RepeatDecoratedText(<span class="string">"Nish"</span>, <span class="string">"Mr."</span> <span class="number">2</span>);
RepeatDecoratedText(<span class="string">"Ant"</span>, <span class="string">"Mr."</span>, <span class="number">2</span>);
RepeatDecoratedText(<span class="string">"Ant"</span>, <span class="string">"The Super"</span>, <span class="number">2</span>);</pre>
<p>So basically, the parameters are either filled in via the named values provided or via the default optional values. Note that you can write optional value methods using attributes too. Example:</p>
<pre><span class="keyword">public</span> <span class="keyword">void</span> RepeatTextDuplicate(<span class="keyword">string</span> text, [Optional, DefaultParameterValue(<span class="number">3</span>)] <span class="keyword">int</span> count)
{
    RepeatText(text, count);
}

<span class="comment">// . . .</span>

RepeatTextDuplicate(<span class="string">"Nish"</span>);
RepeatTextDuplicate(<span class="string">"Nishant"</span>, <span class="number">5</span>);</pre>
<p>The MSIL generated for this method is identical to what you&#8217;d have got with the direct C# syntax (used earlier).</p>
<p>As with dynamic types, apparently the biggest beneficiaries of these new named and optional parameter features are developers who interop with Office. Just like in VBScript you can now avoid having to provide optional arguments, and can also provide a named argument directly. For others, optional parameters will definitely help reduce the number of method overloads you need to write, and where there are methods that have more than a few optional parameters, the ability to call them by specifying named parameters will result in cleaner and more legible code.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=187</wfw:commentRss>
		</item>
		<item>
		<title>A quick look at the C# 4.0 dynamic type</title>
		<link>http://blog.voidnish.com/?p=186</link>
		<comments>http://blog.voidnish.com/?p=186#comments</comments>
		<pubDate>Sat, 23 May 2009 01:35:39 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=186</guid>
		<description><![CDATA[VS 2010 Beta 1 includes some C# 4.0 features and though I have been reading about some of the new stuff on various blogs and forums, I only got to play with it very recently. Put simply, the dynamic keyword allows you to declare and use types that are not type-checked during compilation. They are [...]]]></description>
			<content:encoded><![CDATA[<p>VS 2010 Beta 1 includes some C# 4.0 features and though I have been reading about some of the new stuff on various blogs and forums, I only got to play with it very recently. Put simply, the <code>dynamic</code> keyword allows you to declare and use types that are not type-checked during compilation. They are resolved at runtime using the DLR.</p>
<p>Here&#8217;s a simple class that has a <code>dynamic </code>field, a method that has a <code>dynamic </code>argument, and a <code>dynamic </code>property:</p>
<pre><span class="keyword">class</span> Dynamic
{
    <span class="keyword">private</span> dynamic data;

    <span class="keyword">public</span> <span class="keyword">void</span> SetData(dynamic data)
    {
        <span class="keyword">this</span>.data = data;
    }

    <span class="keyword">public</span> dynamic MetaData { <span class="keyword">get</span>; <span class="keyword">set</span>; }

    <span class="keyword">public</span> <span class="keyword">void</span> Display()
    {
        Console.WriteLine(<span class="string">"{0} {1}, {2} {3}"</span>,
            data, data.GetType(), MetaData, MetaData.GetType());
    }
}</pre>
<p>Using the class is quite straightforward:</p>
<pre><span class="keyword">private</span> <span class="keyword">void</span> Foo()
{
    var d = <span class="keyword">new</span> Dynamic();
    d.MetaData = <span class="number">100</span>; &lt;-- Int32
    d.SetData(<span class="number">99</span>); &lt;-- Int32
    d.Display();
    d.MetaData = <span class="number">100f</span>; &lt;-- Single
    d.SetData(<span class="string">"hello"</span>); &lt;-- String
    d.Display();
}</pre>
<p>Notice how I keep using different types at runtime for calling the same methods and properties. If you look at the IL via Reflector, you&#8217;ll see that dynamic types are internally treated as <code>System.Object</code>. Intellisense within VS 2010 will also give you <code>System.Object</code> members since that&#8217;s what they are guaranteed to have.</p>
<p>There are three dynamic calls in the <code>Display</code> method. A nested static class is generated inside the <code>Dynamic </code>class, and it will have one static <code>CallSite&lt;&gt;</code> field per dynamic call. In this case, there are three such fields. Whenever the dynamic calls are made, it&#8217;s these DLR call sites that come into play. An extremely simplified explanation of what happens is that the DLR internally uses reflection to figure out what type the dynamic object is at runtime. There is also caching done so that type-matching (or mapping) is not repeated unnecessarily. Of course the implementation is quite complex and you could probably spend weeks going through the code in Reflector. Note that if you make <code>dynamic </code>calls in a different method, there will be another static class generated - so it seems to be one inner class per method.</p>
<p>Consider the following simple method:</p>
<pre><span class="keyword">public</span> <span class="keyword">void</span> Test()
{
    var type = data.GetType();
}</pre>
<p>A class will be generated similar to the following (I&#8217;ve made this easy to read - so this is not an accurate representation of the generated code):</p>
<pre>[CompilerGenerated]
<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">class</span> SiteContainerForTest
{
    <span class="keyword">public</span> <span class="keyword">static</span> CallSite<Func<CallSite, <span class="keyword">object</span>, <span class="keyword">object</span>>> callSiteGetType;
}</pre>
<p>And the method <code>Test </code>gets compiled into:</p>
<pre><span class="keyword">public</span> <span class="keyword">void</span> Test()
{
    <span class="keyword">if</span> (SiteContainerForTest.callSiteGetType == <span class="keyword">null</span>)
    {
        SiteContainerForTest.callSiteGetType = CallSite&lt;Func&lt;CallSite, <span class="keyword">object</span>, <span class="keyword">object</span>&gt;&gt;.Create(
            <span class="keyword">new</span> CSharpInvokeMemberBinder(
                CSharpCallFlags.None,
                <span class="string">"GetType"</span>, &lt;-- the name of the dynamic member
                <span class="keyword">typeof</span>(Dynamic),
                <span class="keyword">null</span>,
                <span class="keyword">new</span> CSharpArgumentInfo[] { <span class="keyword">new</span> CSharpArgumentInfo(CSharpArgumentInfoFlags.None, <span class="keyword">null</span>) }
            )
        );
    }

    <span class="keyword">object</span> type = SiteContainerForTest.callSiteGetType.Target(
      SiteContainerForTest.callSiteGetType,
      <span class="keyword">this</span>.data &lt;-- the dynamic <span class="keyword">object</span>
    );
}</pre>
<p>The call site&#8217;s <code>Target </code>will be of type <code>Func&lt;CallSite, object, object&gt;</code>, and the return type is <code>object </code>(because at compile time that&#8217;s what the local variable type was defined as, since we don&#8217;t know what type it would be at that time). It&#8217;s at this point that dynamic binding is done. Fortunately for us, it&#8217;s all done behind the scenes and we are protected from having to write all this code ourselves. Assuming data is an <code>Int32 </code>at this time, <code>Int32</code>&#8217;s <code>GetType </code>is called (and since it doesn&#8217;t have one, <code>Object</code>&#8217;s <code>GetType </code>is invoked).</p>
<p>You can also use <code>dynamic </code>types locally (a site container class is generated for the containing method) :</p>
<pre>dynamic d = <span class="number">1</span>;
<span class="keyword">string</span> s = d.ToString();
Console.WriteLine(s);

d = <span class="string">"dynamic data"</span>;
Console.WriteLine(d.Length);

d = <span class="number">33</span>;

<span class="keyword">try</span>
{
    <span class="keyword">int</span> len = d.Length; &lt;-- Invalid dynamic call on an Int32 <span class="keyword">object</span>
}
<span class="keyword">catch</span> (RuntimeBinderException ex)
{
    Console.WriteLine(ex.Message);
}</pre>
<p>When I try to use the non-existent <code>Length </code>property on an <code>Int32 </code>value, the runtime will throw a <code>RuntimeBinderException</code>. And it even gives a very useful error message : <em>&#8216;int&#8217; does not contain a definition for &#8216;Length&#8217;</em>.</p>
<p>Overall, one of the most celebrated uses of <code>dynamic </code>types is supposed to be for Office interop. You no longer have to do endless casts and mid-level variables for debugging. It&#8217;s just as easy as using classic VBScript. At this point, unless you want to interop with Word or Excel, I can&#8217;t think of too many scenarios where this will come in handy. Maybe someone who&#8217;s more functionally oriented than I am can think of some common scenarios.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=186</wfw:commentRss>
		</item>
		<item>
		<title>Tip : Flush the keyboard buffer from C#</title>
		<link>http://blog.voidnish.com/?p=185</link>
		<comments>http://blog.voidnish.com/?p=185#comments</comments>
		<pubDate>Tue, 19 May 2009 20:15:17 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=185</guid>
		<description><![CDATA[Here&#8217;s another tip from an MSDN forum discussion. Someone wanted to know how to flush the keyboard buffer in a C# console application.
Here&#8217;s a simple hack to do this :
private static void FlushKeyboard()
{
    while (Console.In.Peek() != -1)
        Console.In.Read();
}
Now you can use it as follows :
char [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s another tip from an MSDN forum discussion. Someone wanted to know how to flush the keyboard buffer in a C# console application.</p>
<p>Here&#8217;s a simple hack to do this :</p>
<pre><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> FlushKeyboard()
{
    <span class="keyword">while</span> (Console.In.Peek() != -<span class="number">1</span>)
        Console.In.Read();
}</pre>
<p>Now you can use it as follows :</p>
<pre><span class="keyword">char</span> x = (<span class="keyword">char</span>)Console.Read();
FlushKeyboard();
<span class="keyword">char</span> y = (<span class="keyword">char</span>)Console.Read();
Console.WriteLine(<span class="string">"{0}, {1}"</span>, x, y);</pre>
<p>Even if you enter more than a single character after the first call to <code>Read()</code>, the second <code>Read()</code> will not be affected.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=185</wfw:commentRss>
		</item>
		<item>
		<title>Tip - Sending multi-line email using the mailto: protocol</title>
		<link>http://blog.voidnish.com/?p=184</link>
		<comments>http://blog.voidnish.com/?p=184#comments</comments>
		<pubDate>Sat, 16 May 2009 02:09:32 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=184</guid>
		<description><![CDATA[A few weeks ago someone asked on the MSDN forums how he could use the mailto: protocol to send a multi-line email. The trick is to use %0D%0A in lieu of \r\n.
Here&#8217;s a small C# code snippet that shows how to do this :
string command = "mailto:abc@abc.com?subject=The Subject&#38;body=Ln 1%0D%0ALn 2";
Process.Start(command);
]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago someone asked on the MSDN forums how he could use the <code>mailto:</code> protocol to send a multi-line email. The trick is to use <code>%0D%0A</code> in lieu of <code>\r\n</code>.</p>
<p>Here&#8217;s a small C# code snippet that shows how to do this :</p>
<pre><span class="keyword">string</span> command = <span class="string">"mailto:abc@abc.com?subject=The Subject&amp;body=Ln 1%0D%0ALn 2"</span>;
Process.Start(command);</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=184</wfw:commentRss>
		</item>
		<item>
		<title>Article : A generic Trictionary class</title>
		<link>http://blog.voidnish.com/?p=183</link>
		<comments>http://blog.voidnish.com/?p=183#comments</comments>
		<pubDate>Thu, 12 Mar 2009 04:15:31 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<category><![CDATA[CLR/.NET BCL]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=183</guid>
		<description><![CDATA[I just published an article on a generic Trictionary class :

A generic Trictionary class [on VoidNish]

The Code Project Mirror



The article describes a Trictionary class that is essentially a dictionary except that for each key there are two values, both of differing types. In many cases instead of doing this, the proper approach would most likely [...]]]></description>
			<content:encoded><![CDATA[<p>I just published an article on a generic <code>Trictionary</code> class :</p>
<ul>
<li><a href="http://www.voidnish.com/Articles/ShowArticle.aspx?code=GenericTrictionary" target="_blank">A generic Trictionary class [on VoidNish]</a>
<ul>
<li><a href="http://www.codeproject.com/KB/cs/GenericTrictionary.aspx" target="_blank">The Code Project Mirror</a></li>
</ul>
</li>
</ul>
<p>The article describes a <code>Trictionary</code> class that is essentially a dictionary except that for each key there are two values, both of differing types. In many cases instead of doing this, the proper approach would most likely to use a <code>struct </code>that would have those two types as members. But there may also be scenarios where you may want to avoid having to unnecessarily create a <code>struct </code>just for this purpose. You could also use an anonymous type, but that&#8217;s really not so different in the sense you still end up having a new type in your assembly. Read the article for more info.</p>
<p>Note that the article was inspired by another <code>Trictionary </code>article on Code Project submitted by Joe Enos. </p>
<ul>
<li><a href="http://www.codeproject.com/KB/cs/Trictionary.aspx" target="_blank">Trictionary - Multi-Value Dictionary by Joe Enos</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=183</wfw:commentRss>
		</item>
		<item>
		<title>System.String and intellisense for Linq extension methods</title>
		<link>http://blog.voidnish.com/?p=182</link>
		<comments>http://blog.voidnish.com/?p=182#comments</comments>
		<pubDate>Sat, 07 Mar 2009 14:46:18 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=182</guid>
		<description><![CDATA[Someone was recently complaining in the MSDN forums that intellisense did not work for strings when it came to the Linq extension methods. If you are wondering what that&#8217;s about, System.String is an IEnumerable&#60;char&#62; so you can do all of the Where, Select operations on any string object. Here&#8217;s a contrived example :
string s = [...]]]></description>
			<content:encoded><![CDATA[<p>Someone was recently complaining in the MSDN forums that intellisense did not work for strings when it came to the Linq extension methods. If you are wondering what that&#8217;s about, <code>System.String</code> is an <code>IEnumerable&lt;char&gt;</code> so you can do all of the <code>Where</code>, <code>Select</code> operations on any <code>string</code> object. Here&#8217;s a contrived example :</p>
<pre><span class="keyword">string</span> s = <span class="string">"What's cooking in Alabama?"</span>;
<span class="keyword">char</span>[] vowels = <span class="keyword">new</span>[] {'a', 'e', 'i', 'o', 'u'};
<span class="keyword">char</span>[] nonVowels = s.Where(c => !vowels.Contains(
    Char.ToLower(c))).ToArray();
Console.WriteLine(<span class="keyword">new</span> <span class="keyword">string</span>(nonVowels));</pre>
<p>You just need to manually type in the method name (like <code>Where</code>) and once you do that you&#8217;ll then start getting intellisense. You just won&#8217;t get it for the starting <code>string</code> object. If you really want it there too, you can use an extra <code>IEnumerable&lt;char&gt;</code> variable and then use that instead of the string. Now you will get full intellisense.</p>
<pre>IEnumerable&lt;<span class="keyword">char</span>&gt; chars = s;</pre>
<p>The <code>String</code> class is already equipped with a lot of useful methods, and there&#8217;s always the <code>Regex</code> class if you really need some complex string manipulation. So I am not sure there are too many scenarios where you&#8217;d actually want to use Linq with a string, but to each his own <img src='http://blog.voidnish.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=182</wfw:commentRss>
		</item>
		<item>
		<title>An interesting week in Seattle</title>
		<link>http://blog.voidnish.com/?p=181</link>
		<comments>http://blog.voidnish.com/?p=181#comments</comments>
		<pubDate>Sat, 07 Mar 2009 00:19:23 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=181</guid>
		<description><![CDATA[Last week I attended the 2009 MVP Summit held at Redmond/Seattle and I&#8217;ve got to say that I had two rather peculiar experiences whilst there. The first incident was on the way to Seattle – it snowed in Atlanta of all things to happen and this resulted in dozens of cancelled and delayed flights. My [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I attended the 2009 MVP Summit held at Redmond/Seattle and I&#8217;ve got to say that I had two rather peculiar experiences whilst there. The first incident was on the way to Seattle – it snowed in Atlanta of all things to happen and this resulted in dozens of cancelled and delayed flights. My flight was scheduled for a 2:30 PM departure and after a 3 1/2 hour delay where they pushed back the boarding time every 30 minutes, we finally boarded at 6 PM. Once we got in the aircraft we waited on the tarmac for another 3 1/2 hours more before take-off as we had to wait in line behind dozens of other flights for de-icing. I am still not sure why they couldn&#8217;t have us wait outside (at the gate) and let us board after the de-icing. The air was pretty stuffy inside because the air-conditioners seemed to be at half power. And after take-off they ran out of food when it was my turn to order - so yeah, that didn&#8217;t help either. It was one of the nastiest experiences I&#8217;ve had in an airport/flight in my entire life – one that I hope will not be repeated in future. </p>
<p>The second incident occurred on Tuesday night (or rather Wednesday morning). I was at the Grand Hyatt (17th floor) and had gone to bed close to 1 AM as I had gone for a late dinner/chat with an old friend. Around 4:30 AM or so this really loud siren came on and an even louder announcement was repeated instructing all occupants to move to the nearest staircase and to descend to the first floor immediately. It was also announced that the elevators were shut down. I wasn&#8217;t sure if it was a fire-emergency or some temporary air-pollution – in any case, I put on my shoes, picked up my laptop and climbed down the 17 set of stairs (16 maybe if they didn&#8217;t have a 13th floor, didn&#8217;t feel like counting then). I found a few dozen equally incredulous folks downstairs wondering what the heck had just happened. We watched the fire-trucks come and the firemen go up – and all this time we were all out on the streets. A few minutes later, they said everything was alright and said we could go back up to our rooms.  There was a further wait of 20 minutes or so as we waited for an engineer to come down and reset the elevator system – and I didn&#8217;t want to climb up the 17 floors, not with my laptop. The worst part of the incident was when we found out that some dim-witted inconsiderate jerk had been smoking in a non-smoking floor which was what set off the fire-alarm.  So they had to evacuate that floor as well as the floors directly above and beneath it. </p>
<p>The nice thing about the trip was that the summit was pretty good, we had some interesting technical sessions, the food was great, and it was good to catch up with some fellow MVPs and Microsoft buddies – some of whom I&#8217;ve only met at Microsoft summits and never outside Redmond.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=181</wfw:commentRss>
		</item>
		<item>
		<title>Simulate a window minimize / memory release in your .NET apps</title>
		<link>http://blog.voidnish.com/?p=180</link>
		<comments>http://blog.voidnish.com/?p=180#comments</comments>
		<pubDate>Thu, 26 Feb 2009 21:46:50 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<category><![CDATA[CLR/.NET BCL]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=180</guid>
		<description><![CDATA[Once in a while you have people complaining in the forums that their .NET applications are not releasing memory but that if they minimize the app and restore it, then the memory usage goes down. Why this happens is explained in this Microsoft KB article :

The working set of an application is trimmed when its [...]]]></description>
			<content:encoded><![CDATA[<p>Once in a while you have people complaining in the forums that their .NET applications are not releasing memory but that if they minimize the app and restore it, then the memory usage goes down. Why this happens is explained in this Microsoft KB article :</p>
<ul>
<li><a href="http://support.microsoft.com/kb/293215" target="_blank">The working set of an application is trimmed when its top-level window is minimized</a></li>
</ul>
<p>You can simulate this in your code too (under extreme conditions when you really need the memory). In my case I had to do this in an app that loaded very large PNG files - once in a while we&#8217;d get a memory exception and then I&#8217;d call this method and retry and it would work. It does sound a bit hack-ish but there was nothing else we could do.</p>
<pre>[DllImport(<span class="string">"kernel32.dll"</span>, EntryPoint = <span class="string">"SetProcessWorkingSetSize"</span>,
  ExactSpelling = <span class="keyword">true</span>, CharSet = CharSet.Ansi, SetLastError = <span class="keyword">true</span>)]
<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">extern</span> <span class="keyword">int</span> SetProcessWorkingSetSize(
  IntPtr process, <span class="keyword">int</span> minimumWorkingSetSize, <span class="keyword">int</span> maximumWorkingSetSize); 

<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> ReleaseUnusedMemory()
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    SetProcessWorkingSetSize(
        System.Diagnostics.Process.GetCurrentProcess().Handle, -<span class="number">1</span>, -<span class="number">1</span>);
}</pre>
<p>I thought it&#8217;d be nice to post this here in case anyone else ever needs this.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=180</wfw:commentRss>
		</item>
		<item>
		<title>Using reflection to invoke a constructor that takes a ref parameter</title>
		<link>http://blog.voidnish.com/?p=179</link>
		<comments>http://blog.voidnish.com/?p=179#comments</comments>
		<pubDate>Wed, 25 Feb 2009 19:41:24 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<category><![CDATA[constructor]]></category>

		<category><![CDATA[invoke]]></category>

		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=179</guid>
		<description><![CDATA[Recently in the MSDN Forums, someone wanted to know how he could use reflection to invoke a constructor that took a ref parameter. Personally I can&#8217;t think of any reason why a constructor would have a ref parameter, and try as I did I could not dig up that thread (neither Google nor MSDN forum [...]]]></description>
			<content:encoded><![CDATA[<p>Recently in the MSDN Forums, someone wanted to know how he could use reflection to invoke a constructor that took a <code>ref</code> parameter. Personally I can&#8217;t think of any reason why a constructor would have a <code>ref</code> parameter, and try as I did I could not dig up that thread (neither Google nor MSDN forum search returns the right thread in the search results). </p>
<p>Anyway his main issue was that he did not know how to get the type of a <code>ref string</code> argument. C# will not let you do <code>typeof(string&#038;)</code> which is what he wanted. The solution was to use <code>Type.GetType("System.String&#038;")</code>. In case anyone ever has this bizarre requirement, here&#8217;s a small sample that shows how this can be done.</p>
<pre><span class="keyword">class</span> A
{
    <span class="keyword">public</span> A(){}

    <span class="keyword">public</span> A(<span class="keyword">ref</span> <span class="keyword">string</span> id)
    {
        id = <span class="string">"AAA"</span>;
    }
}

<span class="keyword">class</span> B
{
    <span class="keyword">public</span> B(){}

    <span class="keyword">public</span> B(<span class="keyword">ref</span> <span class="keyword">string</span> id)
    {
        id = <span class="string">"BBB"</span>;
    }
}

<span class="keyword">class</span> Program
{
    <span class="keyword">static</span> <span class="keyword">void</span> Main()
    {
        <span class="keyword">new</span> Program().Foo();
    }

    <span class="keyword">private</span> <span class="keyword">void</span> Foo()
    {
        <span class="keyword">string</span> s = <span class="string">"SSS"</span>;
        Console.WriteLine(s);
        Bar(<span class="keyword">typeof</span>(A), <span class="keyword">ref</span> s);
        Console.WriteLine(s);
        Bar(<span class="keyword">typeof</span>(B), <span class="keyword">ref</span> s);
        Console.WriteLine(s);
    }

    <span class="keyword">private</span> <span class="keyword">void</span> Bar(Type type, <span class="keyword">ref</span> <span class="keyword">string</span> s)
    {
        var ctor = type.GetConstructor(
          <span class="keyword">new</span> Type[] { Type.GetType(<span class="string">"System.String&amp;"</span>) });
        var arr = <span class="keyword">new</span> <span class="keyword">object</span>[] { s };
        ctor.Invoke(arr);
        s = (<span class="keyword">string</span>)arr[<span class="number">0</span>];
    }
}</pre>
<p>Note how I have to copy back the <code>string</code> from the <code>object</code> array. This is because while the <code>string</code> is passed by <code>ref</code>, it&#8217;s the reference in the array that&#8217;s passed to the constructor - and not the <code>string</code> that was passed as a parameter to the <code>Bar</code> method. The difference may be subtle unless you think about it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=179</wfw:commentRss>
		</item>
		<item>
		<title>Static initialization goof-up</title>
		<link>http://blog.voidnish.com/?p=178</link>
		<comments>http://blog.voidnish.com/?p=178#comments</comments>
		<pubDate>Fri, 20 Feb 2009 23:38:49 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<category><![CDATA[CLR/.NET BCL]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=178</guid>
		<description><![CDATA[I am writing this blog entry as a reminder to myself to be careful when using static fields or properties, and I wanted to document some silliness on my part for posterity. Recently I was working on some code where I wanted to keep track of derived class instances by storing them in a static [...]]]></description>
			<content:encoded><![CDATA[<p>I am writing this blog entry as a reminder to myself to be careful when using static fields or properties, and I wanted to document some silliness on my part for posterity. Recently I was working on some code where I wanted to keep track of derived class instances by storing them in a static list in the base class. The classes I was working on were non-trivial and fairly complex (and the original versions were not even authored by me). So for the sake of this blog entry, I&#8217;ve come up with simplified base and derived classes to explain what happened.   Here&#8217;s what the base class looked like :</p>
<pre><span class="keyword">class</span> Base
{
    <span class="keyword">private</span> <span class="keyword">static</span> List<Base> list = <span class="keyword">new</span> List<Base>();

    <span class="keyword">public</span> <span class="keyword">static</span> List<Base> List
    {
        <span class="keyword">get</span> { <span class="keyword">return</span> Base.list; }
    }

    <span class="keyword">private</span> Base()
    {
        Base.list.Add(<span class="keyword">this</span>);
    }

    <span class="keyword">public</span> <span class="keyword">string</span> Name { <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; }

    <span class="keyword">public</span> Base(<span class="keyword">string</span> name) : <span class="keyword">this</span>()
    {
        <span class="keyword">this</span>.Name = name;
    }
}</pre>
<p>And here&#8217;s what a typical derived class would be like :</p>
<pre><span class="keyword">class</span> Derived : Base
{
    <span class="keyword">public</span> <span class="keyword">static</span> Derived Nish = <span class="keyword">new</span> Derived(<span class="string">"Nish"</span>);
    <span class="keyword">public</span> <span class="keyword">static</span> Derived Andrew = <span class="keyword">new</span> Derived(<span class="string">"Andrew"</span>);
    <span class="keyword">public</span> <span class="keyword">static</span> Derived Megan = <span class="keyword">new</span> Derived(<span class="string">"Megan"</span>);

    <span class="keyword">public</span> Derived(<span class="keyword">string</span> name) : <span class="keyword">base</span>(name)
    {
    }
}</pre>
<p>I thought it was all good, and then ran some code that did an iteration of the list :</p>
<pre><span class="keyword">foreach</span> (Base item <span class="keyword">in</span> Derived.List)
{
    Console.WriteLine(item.Name);
}</pre>
<p>To my tremendous surprise nothing came up and the list was empty. For a full 10 minutes, the idiot that I am, I kept pondering over this and wondering what the heck was going on. Then it hit me just like that. Even though I was accessing <code>Derived.List</code>, that was just a C# syntactic convenience that allowed me to write it that way because <code>Derived</code> did not have a <code>List</code> member at all (the compiler auto-fixes this to <code>Base.List</code> in the generated MSIL). The property was defined on <code>Base</code>, and thus <code>Derived</code> has not been accessed yet when I iterate<code> Derived.List</code>. So <code>Derived</code>&#8217;s static initialization has not even happened yet. Once I realized my folly, fixing it was straight forward, I had to bring down the <code>List</code> property to the <code>Derived</code> class. This meant that every derived class had to do that which was a bit of an annoyance but not so much as to be a show stopper. Here&#8217;s the correct code (for my simplified example) :</p>
<pre><span class="keyword">class</span> Base
{
    <span class="keyword">protected</span> <span class="keyword">static</span> List<Base> list = <span class="keyword">new</span> List<Base>();

    <span class="keyword">private</span> Base()
    {
        Base.list.Add(<span class="keyword">this</span>);
    }

    <span class="keyword">public</span> <span class="keyword">string</span> Name { <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; }

    <span class="keyword">public</span> Base(<span class="keyword">string</span> name) : <span class="keyword">this</span>()
    {
        <span class="keyword">this</span>.Name = name;
    }
}

<span class="keyword">class</span> Derived : Base
{
    <span class="keyword">public</span> <span class="keyword">static</span> Derived Nish = <span class="keyword">new</span> Derived(<span class="string">"Nish"</span>);
    <span class="keyword">public</span> <span class="keyword">static</span> Derived Andrew = <span class="keyword">new</span> Derived(<span class="string">"Andrew"</span>);
    <span class="keyword">public</span> <span class="keyword">static</span> Derived Megan = <span class="keyword">new</span> Derived(<span class="string">"Megan"</span>);

    <span class="keyword">public</span> Derived(<span class="keyword">string</span> name) : <span class="keyword">base</span>(name)
    {
    }

    <span class="keyword">public</span> <span class="keyword">static</span> List<Base> List
    {
        <span class="keyword">get</span> { <span class="keyword">return</span> Base.list; }
    }
}</pre>
<p>Next time you are using static properties in your base classes, just be a little careful - I know I&#8217;ll be.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=178</wfw:commentRss>
		</item>
		<item>
		<title>Follow up to writing enums to a database</title>
		<link>http://blog.voidnish.com/?p=177</link>
		<comments>http://blog.voidnish.com/?p=177#comments</comments>
		<pubDate>Thu, 29 Jan 2009 14:32:31 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=177</guid>
		<description><![CDATA[In my previous blog entry, I had recommended storing enums using their string representations when writing them to a database.  There&#8217;s a caveat there though - the enum names should be guaranteed to remain stable, because if you change the name of an enum member, it breaks the database. For my specific scenario I [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous blog entry, I had recommended storing <code>enum</code>s using their string representations when writing them to a database.  There&#8217;s a caveat there though - the <code>enum</code> names should be guaranteed to remain stable, because if you change the name of an <code>enum</code> member, it breaks the database. For my specific scenario I ended up using <code>enum</code> values with explicit <code>short</code> values, so if the names ever change in future the <code>short</code> values remain the same and thus the database remains consistent.</p>
<p>There are other approaches to solving this too. Reader <a href="http://dreamdotnet.com/" target="_blank">Arnaud Weil</a> suggests having a table for each <code>enum</code> and the <code>enum</code> id from this table is used to refer to the <code>enum</code>s elsewhere in the database. The guys at my current project have a specialized class that emulates <code>enum</code>s and also allows the ability to associate meta-information to each <code>enum</code> value (like an image or a description). A third approach would be to use custom attributes and a type descriptor that&#8217;d extract the meta-information from an <code>enum</code> type. The old adage is true - there are many ways to skin a cat.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=177</wfw:commentRss>
		</item>
		<item>
		<title>Recommendation for writing enums to a database</title>
		<link>http://blog.voidnish.com/?p=176</link>
		<comments>http://blog.voidnish.com/?p=176#comments</comments>
		<pubDate>Wed, 28 Jan 2009 18:21:58 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<category><![CDATA[CLR/.NET BCL]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=176</guid>
		<description><![CDATA[I was reviewing some code and found that there were a few enum types that did not have a None value (which is a recommended practice).  I thought I’d go ahead and add the None values when I found that the enum values were being written to the database via calls to Convert.ToInt32. Of [...]]]></description>
			<content:encoded><![CDATA[<p>I was reviewing some code and found that there were a few <code>enum</code> types that did not have a <code>None</code> value (which is a recommended practice).  I thought I’d go ahead and add the <code>None</code> values when I found that the <code>enum</code> values were being written to the database via calls to <code>Convert.ToInt32</code>. Of course this meant that I could not add a <code>None</code> member as the first value since it’d break the database. If all of the <code>enum</code> members specified explicit <code>int</code> values I probably could still add a <code>None</code> member, but even that is kinda messy. </p>
<p>My recommendation is to store <code>enum</code>s as strings in the database. Now you can change the order of the members, add and remove members etc. with absolutely no issues. Converting between an <code>enum</code> value and its string name is rather trivial too.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=176</wfw:commentRss>
		</item>
		<item>
		<title>Using StyleCop</title>
		<link>http://blog.voidnish.com/?p=175</link>
		<comments>http://blog.voidnish.com/?p=175#comments</comments>
		<pubDate>Fri, 21 Nov 2008 13:22:08 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C#/.NET]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=175</guid>
		<description><![CDATA[I&#8217;ve been using StyleCop for a few weeks now and after I got over the initial shock, I actually like using it now. In the long run, the big thing about using it is that your code looks consistent. Of course, in a small company it&#8217;s easy to get everyone to move to StyleCop, things [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using StyleCop for a few weeks now and after I got over the initial shock, I actually like using it now. In the long run, the big thing about using it is that your code looks consistent. Of course, in a small company it&#8217;s easy to get everyone to move to StyleCop, things may be a tad more difficult convincing a bigger group of people to do so.</p>
<p>Some of the rules may seem odd. For example, StyleCop will warn you if you do :</p>
<pre><span class="keyword">if</span>(someCondition)
    DoSomething();</pre>
<p>You need to put braces around it as :</p>
<pre><span class="keyword">if</span>(someCondition)
{
    DoSomething();
}</pre>
<p>Funnily I used to do this till a few years ago, then I started omitting the braces for single-line <code>if</code>-blocks because that&#8217;s what my colleagues did too. And now I&#8217;ve gone back to using braces. And yes the same rule applies for the <code>else</code> statement too.</p>
<p>I&#8217;ll be blogging more stuff on my StyleCop experiences. This post was just a quick something to break the bloggers-block that&#8217;s infected me the past few months.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=175</wfw:commentRss>
		</item>
		<item>
		<title>WPF : Opaque child windows on a transparent parent background</title>
		<link>http://blog.voidnish.com/?p=174</link>
		<comments>http://blog.voidnish.com/?p=174#comments</comments>
		<pubDate>Mon, 14 Jul 2008 02:57:57 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[Avalon]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=174</guid>
		<description><![CDATA[If you set a parent window&#8217;s Opacity, any child windows can only have an opacity equal to or below the parent window&#8217;s. So if you want to keep the main window background transparent but leave the child controls (such as a text box) fully opaque, it will not work as you expect. One solution (there [...]]]></description>
			<content:encoded><![CDATA[<p>If you set a parent window&#8217;s <code>Opacity</code>, any child windows can only have an opacity equal to or below the parent window&#8217;s. So if you want to keep the main window background transparent but leave the child controls (such as a text box) fully opaque, it will not work as you expect. One solution (there are possibly others too) is to do the following.</p>
<p>Set the main window&#8217;s <code>AllowTransparency </code>to <code>true </code>and set the <code>Background </code>to <code>Transparent</code>.</p>
<pre>&lt;Window . . .
    AllowsTransparency=<span class="string">"True"</span> Background=<span class="string">"Transparent"</span>
    &gt;</pre>
<p>Now say you main panel is a grid, put a <code>Border </code>control on it as follows :</p>
<pre>&lt;Border Opacity=<span class="string">"0.9"</span> . . .&gt;
      &lt;Border.Background&gt;
          . . .
      &lt;/Border.Background&gt;
&lt;/Border&gt; </pre>
<p>Set the border&#8217;s background to what you originally wanted the main window&#8217;s background to be. Now you&#8217;ll find a transparent window background where your editable controls can still retain 100% opacity.</p>
<p><strong>Warning </strong>: Setting <code>AllowTransparency </code>to <code>true </code>on the main window potentially results in some very bad performance issues on both XP and Vista since WPF switches to software rendering (in my experience, even with good video cards). Once that happens, animations and video can get pretty unusably slow.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=174</wfw:commentRss>
		</item>
		<item>
		<title>C++/CLI Article : Deriving from a C# disposable class</title>
		<link>http://blog.voidnish.com/?p=173</link>
		<comments>http://blog.voidnish.com/?p=173#comments</comments>
		<pubDate>Sat, 05 Jul 2008 17:24:47 +0000</pubDate>
		<dc:creator>Nish</dc:creator>
		
		<category><![CDATA[C++/CLI]]></category>

		<guid isPermaLink="false">http://blog.voidnish.com/?p=173</guid>
		<description><![CDATA[Last week at work, I had to work on a C++/CLI class that derived from a class written in C# which implemented IDisposable. I got it wrong at first (yeah, same guy who wrote a book on the subject a couple of years ago) and my boss and I spent some time going through the [...]]]></description>
			<content:encoded><![CDATA[<p>Last week at work, I had to work on a C++/CLI class that derived from a class written in C# which implemented <code>IDisposable</code>. I got it wrong at first (yeah, same guy who wrote a book on the subject a couple of years ago) and my boss and I spent some time going through the generated code in Reflector before fixing it up. I came home that night and quickly put together a simple project so I could see the whole picture from a simple perspective. I thought it would benefit others to put together an article reflecting (no pun intended) the issue.</p>
<ul>
<li><a href="http://www.voidnish.com/Articles/ShowArticle.aspx?code=CppDerivingDispose">C++/CLI HowTo : Deriving from a C# disposable class</a></li>
<li><a href="http://www.codeproject.com/KB/mcpp/CppDerivingDispose.aspx" target="_blank">Article mirror on The Code Project</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.voidnish.com/?feed=rss2&amp;p=173</wfw:commentRss>
		</item>
	</channel>
</rss>
