<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' version='2.0'><channel><atom:id>tag:blogger.com,1999:blog-6059435215477995747</atom:id><lastBuildDate>Fri, 22 Jan 2010 10:57:48 +0000</lastBuildDate><title>TimL on C#.NET</title><description>This blog contains information on C#.NET and related technologies.  The topics may range from "the basics" to more advanced topics.</description><link>http://timl.net/</link><managingEditor>noreply@blogger.com (TimL)</managingEditor><generator>Blogger</generator><openSearch:totalResults>46</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-1867723270509969705</guid><pubDate>Wed, 21 Oct 2009 23:25:00 +0000</pubDate><atom:updated>2009-10-21T20:08:57.089-04:00</atom:updated><title>WinForms App Locked Up - Stack shows OnUserPreferenceChanged leading to a WaitOne after unlocking workstation</title><description>Today I had an interesting bug to track down in which an application kept locking up after I locked and then unlocked my workstation.  I was able to attach the debugger, do a "Break All" and then use the Thread and Call Stack windows get a trace stack.  Somewhere down in the .NET framework, the &lt;code&gt;Microsoft.Win32.SystemEvents.OnUserPreferenceChanged&lt;/code&gt; method raised the &lt;code&gt;UserPreferenceChanged&lt;/code&gt; event, and an event handler attached to that event ultimately lead to &lt;code&gt;WaitOne&lt;/code&gt; which was blocking indefinitely on the UI thread.  The top of the callstack looked like this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  [In a sleep, wait, or join] &lt;br /&gt;  mscorlib.dll!System.Threading.WaitHandle.WaitOne(long timeout, bool exitContext) + 0x2f bytes &lt;br /&gt;  mscorlib.dll!System.Threading.WaitHandle.WaitOne(int millisecondsTimeout, bool exitContext) + 0x25 bytes &lt;br /&gt;  System.Windows.Forms.dll!System.Windows.Forms.Control.WaitForWaitHandle(System.Threading.WaitHandle waitHandle = {System.Threading.ManualResetEvent}) + 0x77 bytes &lt;br /&gt;  System.Windows.Forms.dll!System.Windows.Forms.Control.MarshaledInvoke(System.Windows.Forms.Control caller, System.Delegate method, object[] args, bool synchronous) + 0x393 bytes &lt;br /&gt;  System.Windows.Forms.dll!System.Windows.Forms.Control.Invoke(System.Delegate method, object[] args) + 0x50 bytes &lt;br /&gt;  System.Windows.Forms.dll!System.Windows.Forms.WindowsFormsSynchronizationContext.Send(System.Threading.SendOrPostCallback d, object state) + 0x5f bytes &lt;br /&gt;  System.dll!Microsoft.Win32.SystemEvents.SystemEventInvokeInfo.Invoke(bool checkFinalization = true, object[] args = {object[2]}) + 0x62 bytes &lt;br /&gt;  System.dll!Microsoft.Win32.SystemEvents.RaiseEvent(bool checkFinalization = true, object key = {object}, object[] args = {object[2]}) + 0x10f bytes &lt;br /&gt;  System.dll!Microsoft.Win32.SystemEvents.OnUserPreferenceChanged(int msg, System.IntPtr wParam, System.IntPtr lParam) + 0x77 bytes &lt;br /&gt;  System.dll!Microsoft.Win32.SystemEvents.WindowProc(System.IntPtr hWnd = 9111196, int msg = 8218, System.IntPtr wParam = 47, System.IntPtr lParam = 188618224) + 0x2e0 bytes &lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Presumably, whatever was suppose to signal the &lt;code&gt;WaitOne&lt;/code&gt; was also on the main UI thread, so there was a deadlock.  Whatever was wrong was apparently happening deep-down in the framework, as there was nothing in the application source code that ever attached an event handler to the &lt;code&gt;UserPreferenceChanged&lt;/code&gt; event.&lt;br /&gt;&lt;br /&gt;After Googling for some answers, it became apparent that there was probably a threading problem somewhere in the application (as if you couldn't have assumed that one?).  Apparently, all top-level controls automatically register for the &lt;code&gt;UserPreferenceChanged&lt;/code&gt; event so that they can update themselves when the &lt;code&gt;WM_SETTINGCHANGE&lt;/code&gt; Windows message is received to indicate that desktop properties (color, theme, etc.) have changed.  And, when &lt;code&gt;SystemEvents&lt;/code&gt; raises an event to a partiuclar event handler, it checks to see if it is already on the thread appropriate for the object receiving the event; if it is not, it Invokes over to the appropriate thread.  But, if the thread onto which the event handler is invoked does not have a message pump, a lockup occurs (summarized from From &lt;a target="_new" href="http://kbalertz.com/943139/Windows-Forms-application-freezes-system-settings-changed-workstation-locked.aspx"&gt;kbalertz.com&lt;/a&gt;) because &lt;code&gt;Invoke&lt;/code&gt; waits forever.&lt;br /&gt;&lt;br /&gt;Even with that bit of knowledge, it became difficult to track down the problem.  But, "Burn me now, or burn me later" -- I eventually deteremined that it was caused by a cross-threading issue that occurred earlier in the application; for some reason, Visual Studio did not detect it as a cross-thread exception.  There was a spot in code that used a &lt;code&gt;System.Timers.Timer&lt;/code&gt;, and the callback for the &lt;code&gt;Timer&lt;/code&gt; was not properly marshalling calls over to the UI thread before updating some UI properties.  Somehow, that cross-threading issue "in the past" affected the ability for a some control to process the &lt;code&gt;UserPreferenceChanged&lt;/code&gt; event in the future.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-1867723270509969705?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/10/winforms-app-locked-up-stack-shows.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-2365204835319882142</guid><pubDate>Wed, 07 Oct 2009 21:37:00 +0000</pubDate><atom:updated>2009-10-07T18:03:19.285-04:00</atom:updated><title>InvalidOperationException - "Cross-thread operation not valid..."</title><description>Most C# programmers have probably seen the infamous &lt;code&gt;InvalidOperationException&lt;/code&gt; "Cross-thread operation not valid" exception at one time or another. When you see that, you instantly know that your code tried to access the property of a control from a thread other than the thread on which the control's window handle was created.  If you recall a previous post of mine (or from MSDN), there are actually only a total of four methods and properties on a control that can be access from another thread:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;    &lt;li&gt;InvokeRequired&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;Invoke()&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;BeginInvoke()&lt;/li&gt;&lt;br /&gt;    &lt;li&gt;EndInvoke()&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;Novice programmers may think these cross-thread exceptions are just nuisance messages that can be ignored because they do not happen in the final release build sent to the customer.  That, however, couldn't be further from the truth.  Rather, you should aggressively seek them out and fix them because they can lead to all kinds of unexplained lock-ups and crashes that are difficult to diagnose.  But, in order to find them you have to know when you can see them!&lt;br /&gt;&lt;br /&gt;I use to think that cross-thread exceptions are thrown in debug builds, but not thrown in release builds.  That seems to be the way it works, at first, and makes sense to me as a programmer.  After all, a simple &lt;code&gt;#if (DEBUG)&lt;/code&gt; somewhere down in framework code could easily accomplish that.  But, as I have found out the hard way, it is not that simple.&lt;br /&gt;&lt;br /&gt;Rather, my experimentation has shown that cross-thread exceptions only occur if you actually started the application from within Visual Studio.  If you run a debug build of the application from outside of Visual Studio, you do not get the cross-thread exceptions even if you "attached" Visual Studio to that application via the "Debug | Attach to Process..." menu.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-2365204835319882142?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/10/invalidoperationexception-cross-thread.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-6992152865085278754</guid><pubDate>Wed, 02 Sep 2009 21:14:00 +0000</pubDate><atom:updated>2009-09-02T17:47:21.666-04:00</atom:updated><title>"To Copy or Not to Copy" delegates used to raise events</title><description>There is a long-standing debate amongst C#.NET developers:  &lt;i&gt;When raising an event, should you copy the event delegate first or not?&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public event EventHandler MyEvent;&lt;br /&gt;&lt;br /&gt;private void OnRaiseMyEventWithoutCopy()&lt;br /&gt;{&lt;br /&gt;    if (MyEvent != null)&lt;br /&gt;    {&lt;br /&gt;        MyEvent(this, new EventArgs());&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private void OnRaiseMyEventWithCopy()&lt;br /&gt;{&lt;br /&gt;    EventHandler myEvent = MyEvent;&lt;br /&gt;    if (myEvent != null)&lt;br /&gt;    {&lt;br /&gt;        myEvent(this, new EventArgs());&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;In both cases, you must check to see if the event delegate is &lt;code&gt;null&lt;/code&gt;; if you attempt to invoke a &lt;code&gt;null&lt;/code&gt; delegate you will get a &lt;code&gt;NullReferenceException&lt;/code&gt;.  Once the last event handler has unregistered, the delegate will be null.&lt;br /&gt;&lt;br /&gt;Interestingly, the arguments for doing it one way or another typically involve reasons for not doing it the other way:&lt;br /&gt;&lt;br /&gt;The argument for the "with copy" case basically comes down to this:  If you do not do the copy, the delegate may change to &lt;code&gt;null&lt;/code&gt; after you did the null-check but before the delegate was invoked, and that could be bad.&lt;br /&gt;&lt;br /&gt;The argument for the "without copy" case basically comes down to this:  If you do the copy, then you might invoke an event handler that has already unregistered, and that would be bad.&lt;br /&gt;&lt;br /&gt;Honestly, I have flip-flopped on this several times over the years.  But, I currently believe it to be better to do the copy.  In the tradition of saying something is better this way because it is not doing that:&lt;br /&gt;&lt;br /&gt;1) If you do not do the copy, you still have the potential NullReferenceException issue.  If .NET threw a different type of exception, then you could catch it and ignore it because it would be expected that the last handler may have unregistered before you actually invoked the delegate.  But, since it throws the NullRefernceException which could easily have been thrown by one of the handlers, you should probably let that bubble out so that the code raising the event knows something bad happened.&lt;br /&gt;&lt;br /&gt;2) Whether you do the copy or not, once the framework starts traversing down the invocation list, it's just like doing a copy anyway.  If a handler unregisters for an event while the framework is traversing the list, that handler will still be called.  Therefore, handlers must always be written with the understanding that it can still get called after it has been unregistered.&lt;br /&gt;&lt;br /&gt;Since you cannot prevent issue 2, which is basically what the "without copy" way is &lt;i&gt;trying&lt;/i&gt; to prevent, you should at least do the copy because you can prevent issue 1.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-6992152865085278754?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/09/to-copy-or-not-to-copy-delegates-used.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-4586619562976125592</guid><pubDate>Wed, 19 Aug 2009 18:18:00 +0000</pubDate><atom:updated>2009-08-19T14:32:36.458-04:00</atom:updated><title>Form.Load() override never called</title><description>I came across an issue today that boggled my mind for a few minutes.  I had an apparently normal &lt;code&gt;WinForm's Form&lt;/code&gt;, but the &lt;code&gt;OnLoad()&lt;/code&gt; override was never getting called.  Therefore, the &lt;code&gt;Load&lt;/code&gt; event was never rasied.  &lt;br /&gt;&lt;br /&gt;As it turns out, there was nothing wrong with the form itself, but it was being used in an unconventional way.  For some special-case reasons, the code that caused the form to be displayed was using &lt;code&gt;PInvoke&lt;/code&gt; calls to &lt;code&gt;SetWindowsPos()&lt;/code&gt; and &lt;code&gt;ShowWindow()&lt;/code&gt; instead of calling the &lt;code&gt;Form.Show()&lt;/code&gt; or &lt;code&gt;Form.ShowDialog()&lt;/code&gt; method.  Apparently, because neither &lt;code&gt;Show()&lt;/code&gt; nor &lt;code&gt;ShowDialog()&lt;/code&gt; was used, the &lt;code&gt;OnLoad()&lt;/code&gt; method was never called.&lt;br /&gt;&lt;br /&gt;My solution to this problem was to override the &lt;code&gt;OnVisibleChanged()&lt;/code&gt; method, use a flag field to track whether the initialization code had been executed, and call the initialization code from whithin &lt;code&gt;OnVisibleChanged&lt;/code&gt; if it had not yet been executed and Visble just changed to true.  The flag, of course was then changed to true so the initialization code would not be called again if the form went invisible and then became visible again.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-4586619562976125592?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/08/formload-override-never-called.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-7439862111037088610</guid><pubDate>Thu, 13 Aug 2009 14:53:00 +0000</pubDate><atom:updated>2009-08-13T11:08:48.583-04:00</atom:updated><title>Use Shift+Enter to insert '\n' characters using the Visual Studio resource editor</title><description>This is by no means something new.  It's just something I always forget to do, and forget how to do, so I figured I would post it here so I know where to find it when I need it again.&lt;br /&gt;&lt;br /&gt;I often use hard-coded strings for message boxes, UI strings, etc. when I initially write the code, and then go back later to add all of those hard-coded strings into resource files so that they can get localized.  When adding such strings to resource files, one cannot simply cut and paste it from the source code to the resource file because of the embedded control characters.&lt;br /&gt;&lt;br /&gt;The C# Compiler knows that when it sees &lt;code&gt;"\n"&lt;/code&gt; in a string [ that does not start with &lt;code&gt;'@'&lt;/code&gt; ] it should replace that two-character substring with the &lt;code&gt;'\n'&lt;/code&gt; control character.  However, the resource files are not so smart; the substring &lt;code&gt;"\n"&lt;/code&gt; in a resource string is not converted to the &lt;code&gt;'\n'&lt;/code&gt; control character automatically.  But, you can insert a &lt;code&gt;'\n'&lt;/code&gt; newline control character into the resource string by using Shift+Enter in the Visual Studio resource editor.  (For some reason, I always want to do a Ctrl+Enter but that does not work).&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-7439862111037088610?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/08/use-shiftenter-to-insert-n-characters.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-1574786199332042153</guid><pubDate>Wed, 10 Jun 2009 21:29:00 +0000</pubDate><atom:updated>2009-06-10T18:21:37.897-04:00</atom:updated><title>Dangers of Overloading Methods in Derived Classes</title><description>Like most languages, C# supports &lt;i&gt;method overloading&lt;/i&gt;.  Basically, that simply means that you are allowed to have multiple methods with the same name as long as the prototypes (method signatures) are different.  In theory, the compiler chooses the "best" method based on the parameters passed into the method.  And, it generally does a good job.  But, if the overloaded methods are distributed across several classes derived from one another, the compiler may not always choose the method you expect!&lt;br /&gt;&lt;br /&gt;Consider the example below.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public class BaseClass1&lt;br /&gt;{&lt;br /&gt;    public int MyMethod(int x)&lt;br /&gt;    {&lt;br /&gt;        return x - 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class DerivedClass1 : BaseClass1&lt;br /&gt;{&lt;br /&gt;    public int MyMethod(object obj)&lt;br /&gt;    {&lt;br /&gt;        return (int)obj + 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;DerivedClass1 dc1 = new DerivedClass1();&lt;br /&gt;int x1 = 100;&lt;br /&gt;int y1 = dc1.MyMethod(x1);  // y1 == 101&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Given the example above, you might expect &lt;code&gt;y1&lt;/code&gt; to be &lt;code&gt;99&lt;/code&gt; because &lt;code&gt;MyMethod(int)&lt;/code&gt; is a better match than &lt;code&gt;MyMethod(obj)&lt;/code&gt;.  But, if that is what you thought then you would be wrong.  The reality is that &lt;code&gt;y1 == 101&lt;/code&gt; because the compiler chooses &lt;code&gt;MyMethod(obj)&lt;/code&gt; over &lt;code&gt;MyMethod(int)&lt;/code&gt; from the base class.&lt;br /&gt;&lt;br /&gt;The same thing applies if the method is virtual:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public class BaseClass2&lt;br /&gt;{&lt;br /&gt;    public virtual int MyMethod(int x)&lt;br /&gt;    {&lt;br /&gt;        return x - 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class DerivedClass2 : BaseClass2&lt;br /&gt;{&lt;br /&gt;    public virtual int MyMethod(object obj)&lt;br /&gt;    {&lt;br /&gt;        return (int)obj + 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;DerivedClass2 dc2 = new DerivedClass2();&lt;br /&gt;int x2 = 100;&lt;br /&gt;int y2 = dc2.MyMethod(x2);  // y2 == 101&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;In the case of virtual methods above, it seems like you could override the &lt;code&gt;MyMethod(int)&lt;/code&gt; from the base class to fix the problem.  But, if that's what you think, then you would be wrong again.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public class BaseClass3&lt;br /&gt;{&lt;br /&gt;    public virtual int MyMethod(int x)&lt;br /&gt;    {&lt;br /&gt;        return x - 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class DerivedClass3 : BaseClass3&lt;br /&gt;{&lt;br /&gt;    public override int MyMethod(int x)&lt;br /&gt;    {&lt;br /&gt;        return base.MyMethod(x);&lt;br /&gt;    }&lt;br /&gt;        &lt;br /&gt;    public virtual int MyMethod(object obj)&lt;br /&gt;    {&lt;br /&gt;        return (int)obj + 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;DerivedClass3 dc3 = new DerivedClass3();&lt;br /&gt;int x3 = 100;&lt;br /&gt;int y3 = dc3.MyMethod(x3);  // y3 == 101&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;The same applies if the method is &lt;code&gt;static&lt;/code&gt;.  Although, in the case of static methods you &lt;i&gt;might&lt;/i&gt; have expected that because you are specifically scoping to the class name.  But, on the other had, &lt;code&gt;public static&lt;/code&gt; methods of a base class are also available as &lt;code&gt;public static&lt;/code&gt; methods on the derived class, so you &lt;i&gt;might&lt;/i&gt; still have expected the compiler to choose &lt;code&gt;MyMethod(int)&lt;/code&gt; over &lt;code&gt;MyMethod(object)&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public class BaseClass4&lt;br /&gt;{&lt;br /&gt;    public static int MyMethod(int x)&lt;br /&gt;    {&lt;br /&gt;        return x - 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class DerivedClass4 : BaseClass4&lt;br /&gt;{       &lt;br /&gt;    public static int MyMethod(object obj)&lt;br /&gt;    {&lt;br /&gt;        return (int)obj + 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int x4 = 100;&lt;br /&gt;int y4 = DerivedClass4.MyMethod(x4);  // y4 == 101&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;I have not really found a good solution to this problem.  Luckily, it does not occur often (for me) because I generally do not distribute overloaded methods across multiple class.  But, if I do need to do something like that, the only solution I have found is really just a workaround: use the &lt;code&gt;ref&lt;/code&gt; keyword to help the compiler pick the right method; since the compiler knows it has to pass the parameter both in and out, it tends to do the method selection better.  Although, I would hate to have to do that because it introduces a "new danger" of allowing the method to change the value.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public class BaseClass5&lt;br /&gt;{&lt;br /&gt;    public virtual int MyMethod(ref int x)&lt;br /&gt;    {&lt;br /&gt;        return x - 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class DerivedClass5 : BaseClass5&lt;br /&gt;{&lt;br /&gt;    public virtual int MyMethod(ref object obj)&lt;br /&gt;    {&lt;br /&gt;        return (int)obj + 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;DerivedClass5 dc5 = new DerivedClass5();&lt;br /&gt;int x5 = 100;&lt;br /&gt;int y5 = dc5.MyMethod(ref x5);  // y5 == 99&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-1574786199332042153?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/06/dangers-of-overloading-methods-in.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-7884900379560299602</guid><pubDate>Thu, 26 Mar 2009 21:25:00 +0000</pubDate><atom:updated>2009-03-26T17:37:26.198-04:00</atom:updated><title>Nullable Parameters in Public Interfaces</title><description>As discussed in previous posts, C# now has the concept of &lt;i&gt;nullable value types&lt;/i&gt; via the &lt;code&gt;?&lt;/code&gt; operator.  When used correctly, they can be very useful and solve some problems.  But, quite honestly, I feel that they're kind of "hackish" to use them in public methods and interfaces.  In many cases, you can simply make a few quick overloads to cleanup things up a bit.&lt;br /&gt;&lt;br /&gt;Conside, for example, a class with the following public method that uses a paremeter of type &lt;code&gt;int?&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public void MyMethod(int? myParameter)&lt;br /&gt;{&lt;br /&gt;   ...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp; &lt;br /&gt;&lt;br /&gt;Rather than exposing that method for use by others, it could instead be made &lt;code&gt;private&lt;/code&gt; and we could define a couple of &lt;code&gt;public&lt;/code&gt; overloads.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public void MyMethod()&lt;br /&gt;{&lt;br /&gt;    MyMethod();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public void MyMethod(int myParameter)&lt;br /&gt;{&lt;br /&gt;    MyMethod(myParameter as int?);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private void MyMethod(int? myParameter)&lt;br /&gt;{&lt;br /&gt;   ...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp; &lt;br /&gt;&lt;br /&gt;That code is pretty straight forward.  The only trick is to cast the parameter as a &lt;code&gt;int?&lt;/code&gt; before calling the private overload that does all the work.  If you do not do that, then you will very quickly encounter a stack overflow.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-7884900379560299602?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/03/nullable-parameters-in-public.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-6644104948140502548</guid><pubDate>Wed, 25 Mar 2009 01:26:00 +0000</pubDate><atom:updated>2009-03-24T22:19:52.650-04:00</atom:updated><title>Inner Classes for Organization</title><description>C#.NET allows you to define inner classes.  An &lt;i&gt;inner class&lt;/i&gt; is defined within the scope of another class.  There are all kinds of cool things you can do with them.  But, one of the most basic uses is to simply an inner class as an organizational container.&lt;br /&gt;&lt;br /&gt;For example, lets say we have a class that implements the &lt;code&gt;System.ComponentModel.INotifyPropertyChanged&lt;/code&gt; interface.  That interface has a single member -- the &lt;code&gt;PropertyChanged&lt;/code&gt; event of type &lt;code&gt;PropertyChangeEventHandler&lt;/code&gt;.  The &lt;code&gt;PropertyChangedEventHandler&lt;/code&gt;, in turn, uses &lt;code&gt;PropetyChangeEventArgs&lt;/code&gt; as the event arguments, and the &lt;code&gt;PropertyChangedEventArgs&lt;/code&gt; don't tell you much except the name of the property that changed.  &lt;br /&gt;&lt;br /&gt;If our class is going to implement &lt;code&gt;INotifyPropertyChanged&lt;/code&gt;, it also follows that we probably need to define some constants (or static readonly fields) for the various properties that may raise the &lt;code&gt;PropertyChanged&lt;/code&gt; event.&lt;br /&gt;&lt;br /&gt;The traditional approach would be to write a class something like the one shown below.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public class Class1a : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    public static readonly string MyFirstPropertyName = "MyFirstProperty";&lt;br /&gt;    public static readonly string MySecondPropertyName = "MySecondProperty";&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;&lt;br /&gt;    ...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;But, there is no reason why we couldn't (and shouldn't) encaspulate those property constants into their own container via an inner class.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public class Class1b : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    public static class PropertyNames&lt;br /&gt;    {&lt;br /&gt;        public static readonly string MyFirstProperty = "MyFirstProperty";&lt;br /&gt;        public static readonly string MySecondProperty = "MySecondProperty";&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;&lt;br /&gt;    ...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;In the first example, the constant can be accessed with syntax like &lt;code&gt;Class1a.MyFirstPropertyName&lt;/code&gt;.  In the second example, the syntax is a bit more verbose but perhaps easier to use, especially with the context-sensitive drop downs of Visual Studio: &lt;code&gt;Class1b.PropertyNames.MyFirstProperty&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;In the second example, note that the inner class is defined with the &lt;code&gt;static&lt;/code&gt; keyword.  That is not required, as it basically just serves as a way of making the compiler enforce that the class contains nothing but static members.  That is what we want in this case.  But, the downfall of a &lt;i&gt;static class&lt;/i&gt; -- whether it is an inner class or not -- is that it cannot be derived from any class other than &lt;code&gt;System.Object&lt;/code&gt;.  That prohibits us from doing what I am going to show you next.&lt;br /&gt;&lt;br /&gt;Imagine if the inner class in the second example was not static.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public class Class1c : INotifyPropertyChanged&lt;br /&gt;{&lt;br /&gt;    public class PropertyNames&lt;br /&gt;    {&lt;br /&gt;        public static readonly string MyFirstProperty = "MyFirstProperty";&lt;br /&gt;        public static readonly string MySecondProperty = "MySecondProperty";&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public event PropertyChangedEventHandler PropertyChanged;&lt;br /&gt;&lt;br /&gt;    ...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Now, if we derive a new class from &lt;code&gt;Class1c&lt;/code&gt;, we can also define a new inner class that is derived from the inner class of the base class.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public class MyClass2 : MyClass1c&lt;br /&gt;{&lt;br /&gt;    public new class PropertyNames : Class1c.PropertyNames&lt;br /&gt;    {&lt;br /&gt;        public static readonly string MyThirdProperty = "MyThirdProperty"&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    ...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;That little trick with the inner class derived from the base inner class is pretty cool because the new &lt;code&gt;PropertyNames&lt;/code&gt; class inherits the constants, fields, properties and methods of the base inner class.  Therefore, we can not only access the new constants by &lt;code&gt;MyClass2.PropertyNames.MyThirdProperty&lt;/code&gt;, but also continue to access the old constants with &lt;code&gt;MyClass1c.PropertyNames.MyFirstProperty&lt;/code&gt; or &lt;code&gt;MyClass2.ProprtyNames.MyFirstproperty&lt;/code&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-6644104948140502548?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/03/inner-classes-for-organization.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-1294201137474035146</guid><pubDate>Tue, 24 Mar 2009 03:29:00 +0000</pubDate><atom:updated>2009-03-24T07:20:04.397-04:00</atom:updated><title>Volatile Memory</title><description>With modern computers, volatile and non-volatile memory access becomes a somewhat tricky issue.  A computer may have a number of processors or cores that cache and optimize memory reads and writes directly in the hardware itself.  Likewise, the compiler and runtime may also do some amount of caching and optimization.  As a result of all of this caching and optimization, it is quite possible that writes to physical memory actually occur in order that is different from the order in which those writes appear in source code.  As you might imagine, this can cause problems if the programmer has not taken steps to synchronize access.&lt;br /&gt;&lt;br /&gt;For example, imagine that the following code is running on Thread 1, where both variables are fields of a class.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;// Thread 1&lt;br /&gt;_result = 1;&lt;br /&gt;_done = true;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Next, imagine that the following code is running on Thread 2, and that Thread 2 also has access to those same fields and is waiting for &lt;code&gt;_done&lt;/code&gt; to go &lt;code&gt;true&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;// Thread 2&lt;br /&gt;while (!_done)&lt;br /&gt;{&lt;br /&gt;   Thread.Sleep(1000);&lt;br /&gt;}&lt;br /&gt;int result = _result;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;What would you expect &lt;code&gt;result&lt;/code&gt; to hold after the loop?  Chances are, you would expect it to have a value of &lt;code&gt;1&lt;/code&gt; because &lt;code&gt;_result&lt;/code&gt; is set to &lt;code&gt;1&lt;/code&gt; before &lt;code&gt;_done&lt;/code&gt; is set to &lt;code&gt;true&lt;/code&gt;.  And, chances are you would be right some or most of the time.  But, because of the caching and optimization mentioned above, it is actually possible that &lt;code&gt;_done&lt;/code&gt; will physically be set to &lt;code&gt;true&lt;/code&gt; before &lt;code&gt;_result&lt;/code&gt; has physically be set to &lt;code&gt;1&lt;/code&gt;.  Therefore, it is also possible that Thread 2 will read the old value of &lt;code&gt;_result&lt;/code&gt; after Thread 2 sees the change in &lt;code&gt;_done&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;Potentially even worse, if Thread 1 continues to do some long running operation after setting &lt;code&gt;_done&lt;/code&gt;, because of caching and optimization there is no guarantee that Thread 2 will even see the change to &lt;code&gt;_done&lt;/code&gt;.  Basically, for as long as Thread 1 continues to run, Thread 2 could be essentially deadlocked waiting for &lt;code&gt;_done&lt;/code&gt; to change.&lt;br /&gt;&lt;br /&gt;To get around this potential problem, .NET has the &lt;code&gt;Thread.VolatileRead()&lt;/code&gt; and &lt;code&gt;Thread.VolatileWrite()&lt;/code&gt; methods.  The &lt;code&gt;VolatileWrite()&lt;/code&gt; method causes the data to be written to a memory location immediatly instead of being cached.  Similarly, the &lt;code&gt;VolatileRead()&lt;/code&gt; method cause the memory location to be read directly instead of relying in a cached value.&lt;br /&gt;&lt;br /&gt;If a field is shared between more than one concurrent thread and each of those threads always uses &lt;code&gt;VolatileRead()&lt;/code&gt; and &lt;code&gt;VolatileWrite()&lt;/code&gt; to access the field, the expected results will be achieved because the caching and optimziation issue will be avoided.&lt;br /&gt;&lt;br /&gt;In addition to the &lt;code&gt;Thread.VolatileRead()&lt;/code&gt; and &lt;code&gt;Thread.VolatileWrite()&lt;/code&gt; methods that are part of the .NET framework, the C# language itself has a &lt;code&gt;volatile&lt;/code&gt; keyword that can be used with fields. When &lt;code&gt;volatile&lt;/code&gt; is used, all access to the field essentially goes through &lt;code&gt;VolatileRead()&lt;/code&gt; and &lt;code&gt;VolatileWrite()&lt;/code&gt; without explicitly having to use those methods.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;private volatile bool _done;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;And, the ECMA-334 spec (section 17.4.3) goes even further to say&lt;br /&gt;&lt;br /&gt;&lt;i&gt;A volatile read...is guaranteed to occur prior to any references to memory that occur after it in the instruction sequence.&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;and &lt;br /&gt;&lt;br /&gt;&lt;i&gt;A volatile write...is guaranteed to happen after any memory references prior to the write instruction in the instruction sequence.&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;It is important to note in those statements above that they are really talking about a reference to &lt;i&gt;any&lt;/i&gt; field, not just the one that was marked &lt;code&gt;volatile&lt;/code&gt;.  Thus, in our trivial example, if &lt;code&gt;_done&lt;/code&gt; was marked as &lt;code&gt;volatile&lt;/code&gt;, then the memory for the &lt;code&gt;_result&lt;/code&gt; field is also guaranteed to have been updated before the memory for the &lt;code&gt;_done&lt;/code&gt; field is updated.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;// Thread 1&lt;br /&gt;_result = 1;&lt;br /&gt;_done = true;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;After all of this discussion, you will be delighted to know that you do not actually have to actually use the &lt;code&gt;volatile&lt;/code&gt; keyword or &lt;code&gt;Thread.VolatileRead()&lt;/code&gt; and &lt;code&gt;Thread.VolatileWrite()&lt;/code&gt; method if you don't want to do so.  Each of those techniques implements so-called "acquire semantics" and "release semantics".  But, so does the standard &lt;code&gt;lock&lt;/code&gt; that most people are familiar with.  Therefore, many programmers may be more comfortable doing something like this.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;private object _doneLock = new object();&lt;br /&gt;private bool _done;&lt;br /&gt;&lt;br /&gt;bool Done&lt;br /&gt;{&lt;br /&gt;    get&lt;br /&gt;    {&lt;br /&gt;        lock(_doneLock )&lt;br /&gt;        {&lt;br /&gt;            return _done;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    set&lt;br /&gt;    {&lt;br /&gt;        lock(_doneLock )&lt;br /&gt;        {&lt;br /&gt;            _done = value;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;// Thread 1&lt;br /&gt;_result = 1;&lt;br /&gt;this.Done = true;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;// Thread 2&lt;br /&gt;while (!this.Done)&lt;br /&gt;{&lt;br /&gt;   Thread.Sleep(1000);&lt;br /&gt;}&lt;br /&gt;int result = _result;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Likewise, you can also use the thread-safe &lt;code&gt;Interlocked&lt;/code&gt; class methods which also use the acquire and release semantics, but I still suspect most programmers will be happy to stick with the basic &lt;code&gt;lock&lt;/code&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-1294201137474035146?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/03/volatile-memory.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-4259864056957170515</guid><pubDate>Tue, 17 Mar 2009 21:27:00 +0000</pubDate><atom:updated>2009-03-23T21:37:53.470-04:00</atom:updated><title>"const" vs "static readonly"</title><description>A class can have some fields marked with the keyword &lt;code&gt;const&lt;/code&gt; and others marked with the keywords &lt;code&gt;static readonly&lt;/code&gt;.  These are conceptually very similar, yet subtly different.  Your choice about which to use must be based on these subtle differences.&lt;br /&gt;&lt;br /&gt;&lt;table&gt;&lt;br /&gt;   &lt;tr&gt;&lt;br /&gt;     &lt;th&gt;property&lt;/th&gt;&lt;br /&gt;     &lt;th&gt;&lt;code&gt;const&lt;/code&gt;&lt;/th&gt;&lt;br /&gt;     &lt;th&gt;&lt;code&gt;static readonly&lt;/code&gt;&lt;/th&gt;&lt;br /&gt;   &lt;/tr&gt;&lt;br /&gt;   &lt;tr&gt;&lt;br /&gt;     &lt;td&gt;evaluation time&lt;/td&gt;&lt;br /&gt;     &lt;td&gt;The value of a &lt;code&gt;const&lt;/code&gt; field is determined at &lt;i&gt;compile-time&lt;/i&gt;.&lt;/td&gt;&lt;br /&gt;     &lt;td&gt;The value of a &lt;code&gt;static readonly&lt;/code&gt; field is determined at &lt;i&gt;run-time&lt;/i&gt;.&lt;/td&gt;&lt;br /&gt;   &lt;/tr&gt;&lt;br /&gt;   &lt;tr&gt;&lt;br /&gt;     &lt;td&gt;types&lt;/td&gt;&lt;br /&gt;     &lt;td&gt;The type for a &lt;code&gt;const&lt;/code&gt; field must be a &lt;code&gt;sbyte&lt;/code&gt;, &lt;code&gt;byte&lt;/code&gt;, &lt;code&gt;short&lt;/code&gt;, &lt;code&gt;ushort&lt;/code&gt;, &lt;code&gt;int&lt;/code&gt;, &lt;code&gt;uint&lt;/code&gt;, &lt;code&gt;long&lt;/code&gt;, &lt;code&gt;ulong&lt;/code&gt;, &lt;code&gt;char&lt;/code&gt;, &lt;code&gt;float&lt;/code&gt;, &lt;code&gt;double&lt;/code&gt;, &lt;code&gt;decimal&lt;/code&gt;, &lt;code&gt;bool&lt;/code&gt;, &lt;code&gt;string&lt;/code&gt;, an &lt;i&gt;enum type&lt;/i&gt;, or a &lt;i&gt;reference type&lt;/i&gt;.&lt;/td&gt;&lt;br /&gt;     &lt;td&gt;The type for &lt;code&gt;static readonly&lt;/code&gt; field can be anything, including a &lt;code&gt;struct&lt;/code&gt; or an instance of an object allocated via the &lt;code&gt;new&lt;/code&gt; operator.&lt;/td&gt;&lt;br /&gt;   &lt;/tr&gt;&lt;br /&gt;   &lt;tr&gt;&lt;br /&gt;      &lt;td&gt;reference types&lt;/td&gt;&lt;br /&gt;      &lt;td&gt;Although a &lt;code&gt;const&lt;/code&gt; can technically be a &lt;i&gt;reference type&lt;/i&gt;, the only reference type it can be is a &lt;code&gt;string&lt;/code&gt; or &lt;code&gt;null&lt;/code&gt; since the &lt;code&gt;new&lt;/code&gt; operator cannot be used to create an instance of an object at compile-time.&lt;/td&gt;&lt;br /&gt;      &lt;td&gt;Because a &lt;code&gt;static readonly&lt;/code&gt; field is determined at run-time, it can hold a reference to an object allocated via the &lt;code&gt;new&lt;/code&gt; operator.  However, since it is both &lt;code&gt;static&lt;/code&gt; and &lt;code&gt;readonly&lt;/code&gt;, it must be assigned in the declaration and/or &lt;i&gt;static constructor&lt;/i&gt;.&lt;/td&gt;&lt;br /&gt;   &lt;/tr&gt;&lt;br /&gt;   &lt;tr&gt;&lt;br /&gt;      &lt;td&gt;switch statements&lt;/td&gt;&lt;br /&gt;      &lt;td&gt;A &lt;code&gt;const&lt;/code&gt; field &lt;b&gt;can&lt;/b&gt; be used as a &lt;code&gt;case&lt;/code&gt; in a &lt;code&gt;switch&lt;/code&gt; statement because the compiler is able to determine the value to enter in the jump table.&lt;br /&gt;      &lt;td&gt;A &lt;code&gt;static readonly&lt;/code&gt; field &lt;b&gt;cannot&lt;/b&gt; be used as a &lt;code&gt;case&lt;/code&gt; in a switch statement since the value was not known at compile time.&lt;br /&gt;   &lt;/tr&gt;&lt;br /&gt;   &lt;tr&gt;&lt;br /&gt;      &lt;td&gt;Other Assemblies&lt;/td&gt;&lt;br /&gt;      &lt;td&gt;At compile-time, the compiler obtains the value of a &lt;code&gt;const&lt;/code&gt; and inserts it directly into the compiled output of the code that references the constant.  &lt;b&gt;This can have undesirable results!&lt;/b&gt;  Assume, for example, that const is defined in assembly A1 and is used in assembly A2.  &lt;i&gt;If assembly A1 is recompiled and redistributed without also recompiling and redistributing assembly A2&lt;/i&gt;, then A2 will continue to use the old value of the constant that was in affect at the time assembly A2 was last compiled. &lt;/td&gt;&lt;br /&gt;      &lt;td&gt;Since a &lt;code&gt;static readonly&lt;/code&gt; field is assigned and obtained at run-time, other assemblies that reference that field will always use the most recent value of that field instead of obtaining the value at the time the assembly was compiled.&lt;/td&gt;&lt;br /&gt;   &lt;/tr&gt;&lt;br /&gt;&lt;br /&gt;&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-4259864056957170515?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/03/const-vs-static-readonly.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-6157640136286957546</guid><pubDate>Tue, 03 Mar 2009 03:01:00 +0000</pubDate><atom:updated>2009-03-03T00:06:44.747-05:00</atom:updated><title>Raising Events</title><description>Raising events is a pretty fundamental thing on the .NET world.  There has been quite a bit of discussion in various blogs, forums and publications about the proper way to do it.  In particular, there has been a great deal of discussion about whether you should or should not copy the delegate before invoking the delegate.  This post contains my 2&amp;cent; on the subject.&lt;br /&gt;&lt;br /&gt;Consider a simple class with a simple event &lt;code&gt;MyEvent&lt;/code&gt;.  To raise the event from within the class in which it is defined, code needs to simply call the event directly as shown in &lt;code&gt;SomeMethod()&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;class MyBaseClass&lt;br /&gt;{&lt;br /&gt;    public event EventHandler MyEvent;&lt;br /&gt;&lt;br /&gt;    ...&lt;br /&gt;&lt;br /&gt;    private void SomeMethod()&lt;br /&gt;    {&lt;br /&gt;        ...&lt;br /&gt;        MyEvent( this, new EventArgs() );&lt;br /&gt;        ...&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;As discussed in my previous post entitled &lt;i&gt;Events vs Delegates&lt;/i&gt;, the &lt;code&gt;event&lt;/code&gt; keyword is basically a security measure that prevents code outside of the class from raising the event.  That means that classes derived from the class that defines the event cannot raise the event; in fact, derived class cannot even do anything more than call the &lt;code&gt;+=&lt;/code&gt; and &lt;code&gt;-=&lt;/code&gt; operators on that event.&lt;br /&gt;&lt;br /&gt;Rather than calling the event directly as in &lt;code&gt;SomeMethod()&lt;/code&gt; above, the defactor-standard is to define an &lt;code&gt;OnEvent&lt;/code&gt; method to raise the event. Addditionally, such &lt;code&gt;OnEvent&lt;/code&gt; methods are typically made virtual so that derived class can "trap" the event by simply overriding the method without actually having to attach an event handler.  Then, the override method in the derived class simply calls the virtual method in the base class to actually raise the event to other code that has attached event handlers.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;class MyBaseClass&lt;br /&gt;{&lt;br /&gt;    public event EventHandler MyEvent;&lt;br /&gt;&lt;br /&gt;    ....&lt;br /&gt;&lt;br /&gt;    private void SomeMethod()&lt;br /&gt;    {&lt;br /&gt;        ...&lt;br /&gt;        OnMyEvent( new EventArgs() );&lt;br /&gt;        ...&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected virtual void OnMyEvent( EventArgs args )&lt;br /&gt;    {&lt;br /&gt;        MyEvent( this, args );&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class MyDerivedClass : MyBaseClass&lt;br /&gt;{&lt;br /&gt;    ....&lt;br /&gt;&lt;br /&gt;    protected override void OnMyEvent( EventArgs args )&lt;br /&gt;    {&lt;br /&gt;        // Process the event&lt;br /&gt;        ....&lt;br /&gt;&lt;br /&gt;        // Call the base class to raise the event&lt;br /&gt;        base.OnMyEvent( args );&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;In addition to allowing the derived class to trap the event without attaching an event handler, there are other bennefits of using an &lt;code&gt;OnEvent&lt;/code&gt; method to raise the event. In particular, there are some additonal things that need to be done before actually raising the event.  And, if the event was called directly from &lt;code&gt;SomeMethod()&lt;/code&gt; instead of going through an &lt;code&gt;OnEvent&lt;/code&gt;method, then that logic would have to be repeated everywhere the event is raised.&lt;br /&gt;&lt;br /&gt;For starters, there is no guarantee that there are actually any event handlers attached to the event.  And, if the event is called without any attached handlers, an exception will occur.  Therefore, we need to make sure the event is not null before caling it.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;protected virtual void OnMyEvent( EventArgs args )&lt;br /&gt;{&lt;br /&gt;    // Exit if there are no attached handlers&lt;br /&gt;    if (this.MyEvent == null)&lt;br /&gt;    {&lt;br /&gt;        return;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Raise the event&lt;br /&gt;    MyEvent( this, args );&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;But, there is a hidden "cotcha" in the code above.  That is, if the program is threaded (as most real programs are), then it is quite possible that the &lt;code&gt;MyEvent&lt;/code&gt; event may have had one or more attached handlers when the condition was checked, but may no longer have any attached handlers by the time &lt;code&gt;MyEvent( args )&lt;/code&gt; is executed.&lt;br /&gt;&lt;br /&gt;Because of this, many people recommend copying the event into another delegate, and then checking and calling the copy in that delegate.  This works because delegates are value type variables.  Therefore, even if handlers have been removed from the event itself by the time the delegae is called, the delegate will still get called without excetion.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;protected virtual void OnMyEvent( EventArgs args )&lt;br /&gt;{&lt;br /&gt;    // Make a copy of all of the handlers attached to the event&lt;br /&gt;    EventHandler myEvent = this.MyEvent;&lt;br /&gt;&lt;br /&gt;    // Exit if there are no attached handlers in the copy&lt;br /&gt;    if (myEvent == null)&lt;br /&gt;    {&lt;br /&gt;        return;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Raise the event&lt;br /&gt;    myEvent( this, args );&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;At first, I was against doing the copy but I have since reformed my ways.  I have always understood why people recommended doing the copy and how it worked.  But, the reason I was against the copy was because I thought it was just as dangerous to call an event handler that had already been removed.  For example, when using the copy, a class may have unregistered the event handler after the copy occurred but before the delegate was called, and that event handler could end up causing some kind of exception because the class no longer expected the handler to be called (variables used in the handler may have been reset to &lt;code&gt;null&lt;/code&gt;, etc.).&lt;br /&gt;&lt;br /&gt;But, I realized that my logic was flawed.  This is because there is no way to protect against it (short of overriding the event &lt;code&gt;add&lt;/code&gt; and &lt;code&gt;remove&lt;/code&gt; to use synchronization).  Once the delegate is called, it essentially makes it's own copy and works on that copy, anyway.  Therefore, even if an event handler was removed, it can always still be called as long as execution of the delegate started before the handler was removed.&lt;br /&gt;&lt;br /&gt;Exception handling around a delegate is also a much debated topic.  Most people recommend wrapping the call to the delegate with a &lt;code&gt;try...catch&lt;/code&gt;, and doing &lt;code&gt;Debug.Assert&lt;/code&gt;, logging, etc. if any exceptions were thrown by the handler methods.  I also recommend this.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;protected virtual void OnMyEvent( EventArgs args )&lt;br /&gt;{&lt;br /&gt;    // Make a copy of all of the handlers attached to the event&lt;br /&gt;    EventHandler myEvent = this.MyEvent;&lt;br /&gt;&lt;br /&gt;    // Exit if there are no attached handlers in the copy&lt;br /&gt;    if (myEvent == null)&lt;br /&gt;    {&lt;br /&gt;        return;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Raise the event&lt;br /&gt;    try&lt;br /&gt;    {&lt;br /&gt;        myEvent( this, args );&lt;br /&gt;    }&lt;br /&gt;    catch(Exception ex)&lt;br /&gt;    {&lt;br /&gt;        Debug.Fail(ex.Message);&lt;br /&gt;        throw; // Some people do the throw, others do not&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Although most people recommend doing the &lt;code&gt;try...catch&lt;/code&gt;, there is debate about whether the exception should be rethrown or not.  The basic argument is this:  If you do not throw the exception, then code raising the event has no idea that something bad happened.  But, since code raising the event has no idea about what handler methods may be attached to the event, it is not likely that any exceptions thrown by those event handler methods could be of use to the code that raised the event.&lt;br /&gt;&lt;br /&gt;My recommend solution is kind of a hybrid of both.  Basically, I prefer to create new exception class to be thrown if an exception occurs while caling a handler method, and setting the handler method's exception as the inner exception.  (I'll leave the somewhat trivial implementation of &lt;code&gt;EventHandlerException&lt;/code&gt; to your imagination.&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;protected virtual void OnMyEvent( EventArgs args )&lt;br /&gt;{&lt;br /&gt;    // Make a copy of all of the handlers attached to the event&lt;br /&gt;    EventHandler myEvent = this.MyEvent;&lt;br /&gt;&lt;br /&gt;    // Exit if there are no attached handlers in the copy&lt;br /&gt;    if (myEvent == null)&lt;br /&gt;    {&lt;br /&gt;        return;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Raise the event&lt;br /&gt;    try&lt;br /&gt;    {&lt;br /&gt;        myEvent( this, args );&lt;br /&gt;    }&lt;br /&gt;    catch(Exception ex)&lt;br /&gt;    {&lt;br /&gt;        Debug.Fail(ex.Message);&lt;br /&gt;        throw new EventHandlerException("MyEvent", ex);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;To me, this makes the most sense because code calling &lt;code&gt;OnMyEvent()&lt;/code&gt; can now reasonably expect to catch an &lt;code&gt;EventHandlerException&lt;/code&gt; if it wants to, and can even look at the inner exception if it does have reason to suspect certain types of exceptions.&lt;br /&gt;&lt;br /&gt;Of course, no matter what you do, the act of raising the exception itself can be abstracted into a separate class so that it behaves consistently for all events.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;class MyClass&lt;br /&gt;{&lt;br /&gt;    public event EventHandler&amp;lt;EventArgs&amp;gt; MyEvent;&lt;br /&gt;&lt;br /&gt;    protected virtual void OnMyEvent(EventArgs args)&lt;br /&gt;    {&lt;br /&gt;        EventHelper&amp;lt;EventArgs&amp;gt;.RaiseEvent(&lt;br /&gt;            EventHadlerExceptionType.ThrowEventHandlerException,&lt;br /&gt;            this,&lt;br /&gt;            this.MyEvent,&lt;br /&gt;            args);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public enum EventHadlerExceptionType&lt;br /&gt;{&lt;br /&gt;    EatException,&lt;br /&gt;    ThrowEventHandlerException,&lt;br /&gt;    ThrowOriginalException&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static class EventHelper&amp;lt;TEventArgs&amp;gt; where TEventArgs : EventArgs&lt;br /&gt;{&lt;br /&gt;    public static void RaiseEvent(&lt;br /&gt;        EventHadlerExceptionType exHandling,&lt;br /&gt;        object sender,&lt;br /&gt;        EventHandler&amp;lt;TEventArgs&amp;gt; theEvent,&lt;br /&gt;        TEventArgs args)&lt;br /&gt;    {&lt;br /&gt;        // No need to copy handlers because delegates are&lt;br /&gt;        // value types.  The delegate has, therefore, already&lt;br /&gt;        // been copied when it was passed in as a parameter.&lt;br /&gt;&lt;br /&gt;        // Exit if there are no attached handlers in the copy&lt;br /&gt;        if (theEvent == null)&lt;br /&gt;        {&lt;br /&gt;            return;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Raise the event&lt;br /&gt;        try&lt;br /&gt;        {&lt;br /&gt;            theEvent(sender, args);&lt;br /&gt;        }&lt;br /&gt;        catch (Exception ex)&lt;br /&gt;        {&lt;br /&gt;            Debug.Fail(ex.Message);&lt;br /&gt;            switch (exHandling)&lt;br /&gt;            {&lt;br /&gt;                case EventHadlerExceptionType.EatException:&lt;br /&gt;                    break;&lt;br /&gt;&lt;br /&gt;                case EventHadlerExceptionType.ThrowEventHandlerException:&lt;br /&gt;                    throw new EventHandlerException(ex);&lt;br /&gt;&lt;br /&gt;                case EventHadlerExceptionType.ThrowOriginalException:&lt;br /&gt;                default:&lt;br /&gt;                    throw;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-6157640136286957546?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/03/raising-events.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-8695699327026145679</guid><pubDate>Thu, 12 Feb 2009 01:06:00 +0000</pubDate><atom:updated>2009-02-12T23:55:52.324-05:00</atom:updated><title>For Loops, Variable Scope and Anonymous Delegates with Outer Variables</title><description>There is no reason why any programming language must support built in looping.  After all, even if &lt;code&gt;for&lt;/code&gt;, &lt;code&gt;foreach&lt;/code&gt;, &lt;code&gt;while&lt;/code&gt; or &lt;code&gt;do&lt;/code&gt; loops do not exist within the language itself, you could always make any of the above with a few variables, conditions and a &lt;code&gt;goto&lt;/code&gt; statement.  But, looping is such any essentially part of computer programming that most languages provide numerous loop constructs.  C#.NET is no exception.&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;for&lt;/code&gt; loop is undoubtably the most used and beloved loop construct.  But, have you ever stopped to think about the details?&lt;br /&gt;&lt;br /&gt;Consider the following code that loops ten times (from x = 0 to x = 9).&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;for (int x = 0; x &lt; 10; x++)&lt;br /&gt;{&lt;br /&gt;    DoSomeStuff();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Given that most basic example above...&lt;br /&gt;&lt;ul&gt;&lt;br /&gt; &lt;li&gt;Do you know the real &lt;i&gt;scope&lt;/i&gt; of variable &lt;code&gt;x&lt;/code&gt;?&lt;/li&gt;&lt;br /&gt; &lt;li&gt;Do you know whether the condition is &lt;i&gt;checked at the beginning or end&lt;/i&gt; of the loop?&lt;/li&gt;&lt;br /&gt; &lt;li&gt;Do you know when variable &lt;code&gt;x&lt;/code&gt; is &lt;i&gt;incremented&lt;/i&gt;?&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;As it turns out, the &lt;code&gt;for&lt;/code&gt; loop is &lt;i&gt;almost&lt;/i&gt; a short hand representation for slightly more verbose code using the dreaded &lt;code&gt;goto&lt;/code&gt; statement.  But, using the &lt;code&gt;goto&lt;/code&gt; leaves little doubt about the scope of the variable, when the condition is checked, and when the variable is incremented.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;int x = 0;&lt;br /&gt;TopOfLoop:&lt;br /&gt;if (x &lt; 10)&lt;br /&gt;{&lt;br /&gt;   DoSomeStuff();&lt;br /&gt;   x++;&lt;br /&gt;   goto TopOfLoop;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;But, in that code above, the variable &lt;code&gt;x&lt;/code&gt; continues to exist after the loop has completed (which is the way some programming languages do work).  In C#, however, a &lt;code&gt;for&lt;/code&gt; is really more like this, where I have added an extra set of curly braces to ensure that &lt;code&gt;x&lt;/code&gt; goes out of scope when the loop is over.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;// Variable x does not exist&lt;br /&gt;{&lt;br /&gt;    int x = 0;  // Now variable x does exist&lt;br /&gt;    TopOfLoop:&lt;br /&gt;    if (x &lt; 10)&lt;br /&gt;    {&lt;br /&gt;       DoSomeStuff();&lt;br /&gt;       x++;&lt;br /&gt;       goto TopOfLoop;&lt;br /&gt;}&lt;br /&gt;// Variable x no longer exists&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;In C#, variables declared in an outer scope are automatically available within the inner scopes.  For example, if you declare a field on a class then it is accessible from within the class methods.  If you declare a variable in a method then it is available inside other scopes within the method, such as within conditions and loops.&lt;br /&gt;&lt;br /&gt;So, why is it important to know that?  For starters, it means that you can declare the loop variable outside of the loop and it will still be available in "loop scope".  And, if you declare it outside of the loop, then you can still access it after the loop has completed.  Plus, it seems to be a bit more efficient to declare a variable outside of the loop body if it will be assigned a new value on every pass through the loop.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;int value1;&lt;br /&gt;for(int q = 0; q &lt; 10; q++)&lt;br /&gt;{&lt;br /&gt;    value1 = GetValue(q);&lt;br /&gt;    int value2 = GetValue(q);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;In the example above, using &lt;code&gt;value1&lt;/code&gt; is more efficient than &lt;code&gt;value2&lt;/code&gt; because &lt;code&gt;value2&lt;/code&gt; goes in and out of scope on each pass, whereas &lt;code&gt;value1&lt;/code&gt; remains in scope the entire time.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;// Variable x does not exist&lt;br /&gt;for (int x = 0; x &lt; 10; x++) // Now variable x does exist&lt;br /&gt;{&lt;br /&gt;    // Variable x still exists&lt;br /&gt;    DoSomeStuff();&lt;br /&gt;}&lt;br /&gt;// Variable x no longer exists&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;int y;                   // Now variable y does exist&lt;br /&gt;for (y = 0; y &lt; 10; y++) // Variable y still exists&lt;br /&gt;{&lt;br /&gt;    // Variable y still exists&lt;br /&gt;    DoSomeStuff();&lt;br /&gt;}&lt;br /&gt;// Variable y still exists&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;// Pretty much the same for variable z as for y,&lt;br /&gt;// but we initialized the loop variable z outside of&lt;br /&gt;// the loop instead of just declaring it outside&lt;br /&gt;// of the loop.&lt;br /&gt;int z = 0;               // Now variable z exists&lt;br /&gt;for ( ; z &lt; 10; z++ )    // Variable z still exists&lt;br /&gt;{&lt;br /&gt;    // Variable z still exists&lt;br /&gt;    DoSomeStuff();&lt;br /&gt;}&lt;br /&gt;// Variable z still exists&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;In addition to the slight performance difference, there can actually be a big difference between declaring something outside of the loop vs. inside the body of the loop.  For example, in the following code, are variables &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;b&lt;/code&gt; and &lt;code&gt;c&lt;/code&gt; always equal when &lt;code&gt;DoSomething()&lt;/code&gt; is called?&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;int a = 0;&lt;br /&gt;for(int b = 0; b &lt; 10;  b++)&lt;br /&gt;{&lt;br /&gt;    int c = a = b;&lt;br /&gt;&lt;br /&gt;    // Are a, b and c equal inside of DoSomething()?&lt;br /&gt;    DoSomething(a, b, c);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Well, ok, that is kind of a trick question.  In that example, they are equal.  But what about in the following example using &lt;code&gt;BeginInvoke&lt;/code&gt;, &lt;code&gt;MethodInvoker&lt;/code&gt; and an anonymous delegate?&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;int a = 0;&lt;br /&gt;for(int b = 0; b &lt; 10;  b++)&lt;br /&gt;{&lt;br /&gt;    int c = a = b;&lt;br /&gt;&lt;br /&gt;    // Are a, b and c equal inside of DoSomething()?&lt;br /&gt;    // NOTE: this.BeginInvoke assumes we are in a WinForm&lt;br /&gt;    this.BeginInvoke(new MethodInvoker(&lt;br /&gt;        delegate() { DoSomething(a, b, c); }));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Now it becomes a much tricker question.  The answer is no, they are not necessarily equal inside of DoSomething()!  Don't believe me?  Create the following method and give it a try.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;private void DoSomething(int aa, int bb, int cc)&lt;br /&gt;{&lt;br /&gt;    if ( (aa != bb) || (aa != cc) || (bb != cc) )&lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine(string.Format("{0}, {1}, {2}", aa, bb, cc));&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;If you ran the loop on the main UI thread, you may suprised to see the following written to the console/output window:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;9, 10, 0&lt;br /&gt;9, 10, 1&lt;br /&gt;9, 10, 2&lt;br /&gt;9, 10, 3&lt;br /&gt;9, 10, 4&lt;br /&gt;9, 10, 5&lt;br /&gt;9, 10, 6&lt;br /&gt;9, 10, 7&lt;br /&gt;9, 10, 8&lt;br /&gt;9, 10, 9&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;What the heck?  Why is &lt;code&gt;a&lt;/code&gt; always &lt;code&gt;9&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; always &lt;code&gt;10&lt;/code&gt;?  The call to &lt;code&gt;this.BeginInvoke()&lt;/code&gt; "schedules" a call to &lt;code&gt;DoSomething(a,b,c)&lt;/code&gt; to be run on the main UI thread via the &lt;code&gt;MethodInvoker&lt;/code&gt; and anonymous delegate.  Variables &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; are declared outside of the loop's body, whereas variable &lt;code&gt;c&lt;/code&gt; is declared within the loop's body.  Therefore, &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; never go out of scope during the entire loop.  But, variable &lt;code&gt;c&lt;/code&gt; goes in and out of scope on each pass through the loop.&lt;br /&gt;&lt;br /&gt;When &lt;code&gt;DoSomething()&lt;/code&gt; finally runs inside an anonymouse delegate on the main UI thread, it gets the current value of the outer variables &lt;code&gt;a&lt;/code&gt;, &lt;code&gt;b&lt;/code&gt; and &lt;code&gt;c&lt;/code&gt;.  If the variable has gone out of scope, then the current value is whatever it's value was when the variable went out of scope.  Since &lt;code&gt;c&lt;/code&gt; goes in and out of scope on each pass through the loop, the value you would expect to be passed into &lt;code&gt;DoSomething()&lt;/code&gt; for &lt;code&gt;c&lt;/code&gt; is passed in (i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9).  But, since &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; do not go out of scope on each pass, their current values at the time &lt;code&gt;DoSomething()&lt;/code&gt; is &lt;i&gt;actually&lt;/i&gt; called are the not the values on that pass through the loop.&lt;br /&gt;&lt;br /&gt;If the loop was run on the main UI thread, then none of the calls to &lt;code&gt;DoSomething()&lt;/code&gt; will occur until the loop has completed.  And, in that case, &lt;code&gt;a&lt;/code&gt; will always be &lt;code&gt;9&lt;/code&gt; (because it was set to 9 on the last pass through the loop) and &lt;code&gt;b&lt;/code&gt; will always be &lt;code&gt;10&lt;/code&gt; because it was incremented to &lt;code&gt;10&lt;/code&gt; before breaking out of the loop.&lt;br /&gt;&lt;br /&gt;But, if the loop is run on the background thread instead of the main UI thread, then the values of &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; becomes a bit more unpredictable.  This is because you never know when a context switch to the main UI thread to call &lt;code&gt;DoSomething()&lt;/code&gt; will actually occur.  It could occur while still running the loop, or after the loop has completed.  And, if the context switch occurs around the time of the assigment &lt;code&gt;c = a = b&lt;/code&gt; then it is possible that &lt;code&gt;b&lt;/code&gt; as not yet been assigned to &lt;code&gt;a&lt;/code&gt; or &lt;code&gt;c&lt;/code&gt;; perhaps &lt;code&gt;b&lt;/code&gt; has even been assigned to &lt;code&gt;a&lt;/code&gt; but not &lt;code&gt;c&lt;/code&gt;.  This may not be so evident with a loop of only 10, but should become more evident if the loop is increased to, say, 100.&lt;br /&gt;&lt;br /&gt;For example, if I run the following code, I will get something slightly different each time.  Note that I use the "delegate BeginInvoke trick" to invoke &lt;code&gt;DoLoop&lt;/code&gt; onto a background thread, and have added a &lt;code&gt;Sleep(0)&lt;/code&gt; about half-way through the loop to make sure a context switch happens at least once so that &lt;code&gt;DoSomething()&lt;/code&gt; has a likely chance to run at least one time on the main UI thread before the loop finishes on the background thread.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;private void button1_Click(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;    MethodInvoker del = new MethodInvoker(DoLoop);&lt;br /&gt;    del.BeginInvoke(DoLoop_Callback, del);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private void DoLoop()&lt;br /&gt;{&lt;br /&gt;    int a = 0;&lt;br /&gt;    for(int b = 0; b &lt; 100;  b++)&lt;br /&gt;    {&lt;br /&gt;        int c = a = b;&lt;br /&gt;        this.BeginInvoke(new MethodInvoker(&lt;br /&gt;            delegate(){&lt;br /&gt;                DoSomething(a, b, c);&lt;br /&gt;            }));&lt;br /&gt;&lt;br /&gt;        &lt;br /&gt;        if( (c % 50) == 0)&lt;br /&gt;        {&lt;br /&gt;            Thread.Sleep(0);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private void DoLoop_Callback(IAsyncResult ar)&lt;br /&gt;{&lt;br /&gt;    MethodInvoker del = ar.AsyncState as MethodInvoker;&lt;br /&gt;    del.EndInvoke(ar);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private void DoSomething(int aa, int bb, int cc)&lt;br /&gt;{&lt;br /&gt;    if ((aa != bb) || (aa != cc) || (bb != cc))&lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine(string.Format("{0}, {1}, {2}", aa, bb, cc));&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;With that code above, I had the following output to the console.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;46, 46, 0&lt;br /&gt;99, 100, 1&lt;br /&gt;99, 100, 2&lt;br /&gt;...&lt;br /&gt;99, 100, 98&lt;br /&gt;99, 100, 99&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;If you run the code multiple times, you may get slightly different results each time.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-8695699327026145679?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2009/02/for-loops-variable-scope-and-anonymous.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-6177437675150516396</guid><pubDate>Thu, 18 Dec 2008 16:53:00 +0000</pubDate><atom:updated>2008-12-30T01:01:21.176-05:00</atom:updated><title>Comparing Default Values In Generic Classes</title><description>Ever since they were introduced in C# 2.0, most programmers have loved generics.  I know I do!  But, it can be a bit tricky to determine if a variable has been assigned or is still the default value if you do not know how to do it.&lt;br /&gt;&lt;br /&gt;Consider the following class, and note that it&lt;br /&gt;&lt;ul&gt;&lt;br /&gt; &lt;li&gt;Is a generic class&lt;br /&gt; &lt;li&gt;Has a field name &lt;code&gt;_field&lt;/code&gt;&lt;br /&gt; &lt;li&gt;Initialize &lt;code&gt;_field&lt;/code&gt; to the default value in the constructor&lt;br /&gt; &lt;li&gt;Has a property &lt;code&gt;IsDefaultValue&lt;/code&gt; that should return true if &lt;code&gt;_field&lt;/code&gt; is still the default value (or has been assigned back the default value).&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;public class MyClass&lt;T&gt;&lt;br /&gt;{&lt;br /&gt;    private T _field;&lt;br /&gt;&lt;br /&gt;    public MyClass()&lt;br /&gt;    {&lt;br /&gt;        _field = default(T);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public T Field&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            return _field;&lt;br /&gt;        }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            _field = value;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public bool IsDefaultValue&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            // The following line does not compile!&lt;br /&gt;            return ( _field == default(T) );&lt;br /&gt;        }    &lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;The code &lt;code&gt;default(T)&lt;/code&gt; causes the compiler to use the default that is appropriate for the type (&lt;code&gt;null&lt;/code&gt; for refrence types, &lt;code&gt;0&lt;/code&gt; for an int, &lt;code&gt;0.0&lt;/code&gt; for a double, etc.).  This is used in the constructor to assign the default value to &lt;code&gt;_field&lt;/code&gt;.  Therefore, it seems logical that we can do a comparison such as &lt;code&gt;( _field == default(T) )&lt;/code&gt;.  But, the compiler does not like it and will complain with a message like &lt;i&gt;Operator '==' cannot be applied to operands of type 'T' and 'T'&lt;/i&gt;.&lt;br /&gt;&lt;br /&gt;So, the question becomes just how do you do such a comparison if you cannot do that?  If you know &lt;code&gt;T&lt;/code&gt; is a reference type, you can compare against &lt;code&gt;null&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;// Works only if T is a reference time&lt;br /&gt;return ( _field == null );&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;But, that will only work for reference types and we have not put any such constraints on &lt;code&gt;T&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;Actually, as a side note, that code will compile for both reference types and value types but will always return false for value types.  This is because, believe it or not, starting with C# 2.0, you can compare any value type to null using the &lt;code&gt;==&lt;/code&gt; operator, but the comparison will always return &lt;code&gt;false&lt;/code&gt;.  This is a side effect of adding support for &lt;i&gt;nullable types&lt;/i&gt; via &lt;code&gt;?&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;int x = 1;&lt;br /&gt;if (x == null)... // Always returns false&lt;br /&gt;&lt;br /&gt;int? y = null;&lt;br /&gt;if (y == null)... // Returns true since y is null&lt;br /&gt;&lt;br /&gt;y = 1;&lt;br /&gt;if (y == null)... // Return false since y is not null&lt;br /&gt;&lt;br /&gt;if (x == y) ...   // Return true since x and y have the same value of 1&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;So, if you cannot compare against &lt;code&gt;default(T)&lt;/code&gt; or &lt;code&gt;null&lt;/code&gt;, what can you do to see if &lt;code&gt;_field&lt;/code&gt; is currently set to the default value?  The best way I have found to do this is shown below.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;    public bool IsDefaultValue&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            return object.Equals(_field, default(T) );&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;With that change to the &lt;code&gt;IsDefaultValue&lt;/code&gt; method, it compiles and works as you would expect.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;MyClass&amp;lt;int&amp;gt; obj1 = new MyClass&amp;lt;int&amp;gt;();&lt;br /&gt;bool flag1a = obj1.IsDefaultValue; // true&lt;br /&gt;obj1.Field = 1;&lt;br /&gt;bool flag1b = obj1.IsDefaultValue; // false&lt;br /&gt;&lt;br /&gt;MyClass&amp;lt;object&amp;gt; obj2 = new MyClass&amp;lt;object&amp;gt;();&lt;br /&gt;bool flag2a = obj2.IsDefaultValue; // true&lt;br /&gt;obj2.Field = new object();&lt;br /&gt;bool flag2b = obj1.IsDefaultValue; // false&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-6177437675150516396?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/12/comparing-default-values-is-generics.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-7848511582566790913</guid><pubDate>Sat, 06 Dec 2008 04:16:00 +0000</pubDate><atom:updated>2008-12-30T01:11:28.793-05:00</atom:updated><title>WPF and TextDecoration</title><description>In WPF, many classes have a &lt;code&gt;TextDecorations&lt;/code&gt; property of type &lt;code&gt;TextDecorationCollection&lt;/code&gt;.  That property is used to add any combination of overline, strike through, underline, baseline or custom decorations to text.  (For the rest of this post, I will be ignoring custom and sticking with the standard four).&lt;br /&gt;&lt;br /&gt;When using XAML, things just kind of automagically work.  The following example reads very nice, and leaves not doubt that the text will be both underlined and overlined.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&amp;lt;TextBlock TextDecorations="Underline, Overline"&amp;gt;&lt;br /&gt;  The quick red fox&lt;br /&gt;&amp;lt;/TextBlock&amp;gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;But, when using text decorations from code, things are a bit on the weird side.&lt;br /&gt;&lt;br /&gt;For starters, consider the following properties of the &lt;code&gt;TextDecorations&lt;/code&gt; static class: &lt;code&gt;TextDecorations.Baseline&lt;/code&gt;, &lt;code&gt;TextDecorations.Overline&lt;/code&gt;, &lt;code&gt;TextDecorations.Strikethrough&lt;/code&gt; and &lt;code&gt;TextDecorations.Underline&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;Sounds like a list of predefined text decorations, so what's weird with that?  I find it very weird that each of those properties is actually of type &lt;code&gt;TextDecprationCollection&lt;/code&gt; which implies it could have multiple items within the collection.&lt;br /&gt;&lt;br /&gt;Presumably, Microsoft chose to make those properties collections so that you could directly set them in code to a &lt;code&gt;TextDecorations&lt;/code&gt; property.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;TextBlock textBlock = new TextBlock();&lt;br /&gt;textBlock.TextDecorations = TextDecorations.Underlined;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;And, they overload the &lt;code&gt;TextDecorationCollection.Add()&lt;/code&gt; method so that it can take an &lt;code&gt;IEnumerable(TextDecoration)&lt;/code&gt; (i.e. another TextDecorationCollection, etc.).&lt;br /&gt;&lt;br /&gt;Now for the part I find very weird.  Let's say I created a TextDecorationCollection instance and added to it &lt;code&gt;TextDecorations.Underline&lt;/code&gt;, and then set a &lt;code&gt;TextDecoration&lt;/code&gt; property to that collection.  Then, if I add or remove TextDecorations to or from the TextDecorationCollection collection after it has already been set to the property, those changes are not rendered.  One way around this is to set the property to null, add the decorations to the collection, and then set it back.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;TextDecorationCollection tdc = &lt;br /&gt;    textBlock.TextDecorations;&lt;br /&gt;&lt;br /&gt;textBlock.TextDecorations = null;&lt;br /&gt;&lt;br /&gt;tds.Add(TextDecorations.Strikethrough);&lt;br /&gt;&lt;br /&gt;textBlock.TextDecorations = tds;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Or, I could also create a new instance using the overload that acts like a copy constructor.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;TextDecorationCollection tdc =&lt;br /&gt;   new TextDecorationCollection(textBlock.TextDecorations);&lt;br /&gt;&lt;br /&gt;tds.Add(TextDecorations.Strikethrough);&lt;br /&gt;&lt;br /&gt;textBlock.TextDecorations = tds;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-7848511582566790913?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/12/wpf-and-textdecoration.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-2524717449690433948</guid><pubDate>Sat, 06 Dec 2008 03:40:00 +0000</pubDate><atom:updated>2008-12-05T23:13:13.484-05:00</atom:updated><title>?, ?? and Casting</title><description>I have previous written a post on the use of the &lt;code&gt;?&lt;/code&gt; and &lt;code&gt;??&lt;/code&gt; operators and &lt;i&gt;nullable types&lt;/i&gt;.  If you recall, you can make any value type &lt;nullable&gt; by declaring it with the &lt;code&gt;?&lt;/code&gt; operator:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;int? myIntA;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Also, you may recall that when you use the value of a nullable type, you must also supply a value to use if the value of the nullable type is null.  If you think about it, this makes perfect sense.  If &lt;code&gt;myIntA&lt;/code&gt; was null in the example above, what the heck does it mean to 100 to &lt;code&gt;myIntA&lt;/code&gt;?  The compiler has no idea, so you must tell it, which is really one of the main reasons why the &lt;code&gt;??&lt;/code&gt; operator was added.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;int myIntB = 100 + (myIntA ?? 0);&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;But what if you already &lt;i&gt;know&lt;/i&gt; the value is not null?  Do you still have to supply a "dummy" value to use for null even though you know it will never be used?  The answer is no, because you could always cast it to a non-nullable type:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;if (myIntA == null)&lt;br /&gt;{&lt;br /&gt;    myIntB = 100;&lt;br /&gt;}&lt;br /&gt;else&lt;br /&gt;{&lt;br /&gt;    myIntB = 100 + (int)myIntA;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;The casting approach is not so handy in the example above because it's just a more verbose way of doing the same calculation, but it does illustrate the point.  And, there are many times, where the casting is the way to go.  For example, what if you wanted to call a different method based on whether the value was &lt;code&gt;null&lt;/code&gt; or not?&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;if (myIntA == null)&lt;br /&gt;{&lt;br /&gt;    Method1();&lt;br /&gt;}&lt;br /&gt;else&lt;br /&gt;{&lt;br /&gt;    Method2( (int)myIntA );&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-2524717449690433948?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/12/and-casting.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-4347002529182908050</guid><pubDate>Thu, 26 Jun 2008 23:24:00 +0000</pubDate><atom:updated>2008-06-26T19:42:19.601-04:00</atom:updated><title>==, .Equals() and ReferenceEquals()</title><description>C#.NET offers a variety of ways of testing for equality.  For the most part, things just work as the programmer would expect.  But, because the &lt;code&gt;==&lt;/code&gt; operator and &lt;code&gt;Equals()&lt;/code&gt; method can be overriden, some guidelines have been established by Microsoft to ensure that things continue to work as expected.&lt;br /&gt;&lt;br /&gt;For starters, just what does the &lt;code&gt;==&lt;/code&gt; operator do?  Well, that depends on what type of data you are dealing.  For the &lt;i&gt;predefined value types&lt;/i&gt;, the &lt;code&gt;==&lt;/code&gt; operator returns true of the values are equal.  For &lt;i&gt;predefined reference types (except strings)&lt;/i&gt;, the &lt;code&gt;==&lt;/code&gt; operator returns true if both sides reference the same object.  And, the &lt;code&gt;System.String&lt;/code&gt; class (a predefined, immutable reference type) overrides the &lt;code&gt;==&lt;/code&gt; operator to return true if both sides have the same value.&lt;br /&gt;&lt;br /&gt;For your own classes, you &lt;i&gt;can&lt;/i&gt; override the &lt;code&gt;==&lt;/code&gt; operator to do a value comparison instead of a reference comparison, but that does not mean you should!  You should seriously think twice before doing that because most programmers will assume it is still a reference comparison.&lt;br /&gt;&lt;br /&gt;If the &lt;code&gt;System.String&lt;/code&gt; overrides &lt;code&gt;==&lt;/code&gt; to compare string values, just what does it mean for two strings to have the same value?  The string's &lt;code&gt;==&lt;/code&gt; operator actually calls the static &lt;code&gt;String.Equals(string, string)&lt;/code&gt; method.  And, that method will return true if...&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;   &lt;li&gt;Both parameters are null&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Both parameters reference the same object&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Both parameters are have the same number of characters (i.e. same length) and the &lt;i&gt;ordinal&lt;/i&gt; value of each character is the same&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;Note that &lt;code&gt;String.Equals()&lt;/code&gt; compares the &lt;i&gt;ordinal value&lt;/i&gt;.  This means that the comparison is inherently &lt;i&gt;case-sensitive&lt;/i&gt; and &lt;i&gt;culture-insensitive&lt;/i&gt;.  That is, the Unicode values of the characters at each position in the two strings must be same.&lt;br /&gt;&lt;br /&gt;Ok, so you can use the &lt;code&gt;==&lt;/code&gt; operator to compare the value of two strings.  But, what if you want actually do want to compare two string variables to see if they reference the same thing?  One common "trick" people do is to cast one (or both) of the string variables to an &lt;code&gt;object&lt;/code&gt;.  Because one side is now an object, the compiler will use &lt;code&gt;System.Object&lt;/code&gt;'s &lt;code&gt;==&lt;/code&gt; operator instead of the &lt;code&gt;System.String&lt;/code&gt; operator to do that comparison, and that operator will do a reference comparison.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;bool flag = (object)a == b;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;That works, but should you do that?  I say "no".  Why?  The reason is simple:  because Visual Studio will underline that code with a green squiggly line, and when you mouse over it the tooltip says "Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'".  Basically, they are telling you that something is "fishy" and that means it does not fall under best practices.&lt;br /&gt;&lt;br /&gt;By now. You may be asking yourself &lt;i&gt;If the cast-trick above is not best practices, how do I compare two strings to see if they reference the same value?&lt;/i&gt; OR, &lt;i&gt;If the &lt;code&gt;==&lt;/code&gt; operator &lt;i&gt;may&lt;/i&gt; have been overridden to compare values, how do I know I am actually comparing references?&lt;/i&gt;  Truth-be-told, the answer to both of those questions is the same:  use the static &lt;code&gt;System.Object.ReferenceEquals()&lt;/code&gt; method instead.&lt;br /&gt;&lt;br /&gt;&lt;i&gt;The &lt;code&gt;Object.ReferenceEquals()&lt;/code&gt; method unequivocally compares two references to see if they reference to the same instance an object.&lt;/i&gt;  With normal objects, this is pretty straight-forward to understand.  But, once again, things actually get a bit tricky with strings as is shown in the example below.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;string a = "12";&lt;br /&gt;string b = "1" + "2";&lt;br /&gt;string c = "1"; c += "2";&lt;br /&gt;&lt;br /&gt;// flagA1, flagA2, flagA3 and flagA4 are all true&lt;br /&gt;// because they were all assigned by value comparisons.&lt;br /&gt;bool flagA1 = (a == "12");&lt;br /&gt;bool flagA2 = (a == a);&lt;br /&gt;bool flagA3 = (a == b);&lt;br /&gt;bool flagA4 = (a == c);&lt;br /&gt;&lt;br /&gt;// flagB1, flagB2 and flagB3 are all true because the&lt;br /&gt;// compiler interns the variables a &amp; b and literal "12"&lt;br /&gt;// to the same string.&lt;br /&gt;bool flagB1 = object.ReferenceEquals(a, "12");&lt;br /&gt;bool flagB2 = object.ReferenceEquals(a, a);&lt;br /&gt;bool flagB3 = object.ReferenceEquals(a, b);&lt;br /&gt;&lt;br /&gt;// flagB4 is false because variable c was created by&lt;br /&gt;// concatenating two values at run-time, and therefore&lt;br /&gt;// is not interned to the same "12" as variables a &amp; b&lt;br /&gt;// literal "12".  Sure, variable b was concatenated too,&lt;br /&gt;// but that was at compile time so it was still interned.&lt;br /&gt;bool flagB4 = object.ReferenceEquals(a, c);&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;There are a few more things to be aware about when it comes to comparisons using the &lt;code&gt;==&lt;/code&gt; operator.  Ever here of boxing and unboxing?  The &lt;code&gt;==&lt;/code&gt; operator will compare the values of two value-type parameters, but boxed parameters are no longer value type parameters!&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;bool CompareBoxedValues(object a, object b)&lt;br /&gt;{&lt;br /&gt;    return (a == b);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int a = 1;&lt;br /&gt;int b = 1;&lt;br /&gt;&lt;br /&gt;// flag1 is true because the two values are equal&lt;br /&gt;bool flag1 = (a == b); &lt;br /&gt;&lt;br /&gt;// flag2 is false because the two variables are boxed&lt;br /&gt;// into different objects&lt;br /&gt;bool flag2 = CompareBoxedValues(a, b);&lt;br /&gt;&lt;br /&gt;// flag3 is also false because the same variable is&lt;br /&gt;// boxed into two different objects&lt;br /&gt;bool flag3 = CompareBoxedValues(a, a);&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;So now think back to that &lt;code&gt;Object.ReferenceEquals()&lt;/code&gt; method.  What do you think happens if you pass non-references (i.e. values) into it?  Sure enough, each value gets boxed into a different object instance so the method always returns false!&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;// The following always sets flag to false&lt;br /&gt;int a = 1;&lt;br /&gt;bool flag = ReferenceEquals(a, a);&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;That pretty much covers a few of the &lt;i&gt;basics&lt;/i&gt; of comparisons in .NET.  But, once again, string comparisons prevent a host of problems.  Do you want to do a case-sensitive or insensitive comparison?  What about cultural based comparisons?  To see if you will get burnt by a Turkey, see the blog post from my colleague &lt;a href="http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html" target="_new"&gt;Jeff Moser&lt;/a&gt; in the office next to me.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-4347002529182908050?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/06/equals-and-referenceequals.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-1988639033416612804</guid><pubDate>Mon, 23 Jun 2008 17:08:00 +0000</pubDate><atom:updated>2008-06-23T13:44:05.217-04:00</atom:updated><title>Statics and Generics</title><description>If you think about it, it makes total sense.  But, this is something you need to be careful of if you are use static member variables inside of generic classes.  Basically, &lt;i&gt;each different type you pass into a generic creates a new class, and each of those classes has its own set of static member variables&lt;/i&gt;!&lt;br /&gt;&lt;br /&gt;As an example, consider the following trivial example class.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class MyGenericClass&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;    private static int s_IdCounter = 0;&lt;br /&gt;&lt;br /&gt;    private int _id;&lt;br /&gt;&lt;br /&gt;    private T _value;&lt;br /&gt;&lt;br /&gt;    public MyGenericClass(T value)&lt;br /&gt;    {&lt;br /&gt;        _id = Interlocked.Increment(ref s_IdCounter);&lt;br /&gt;        _value = T;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public int Id&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            return _id;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public T Value&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            return _value;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Now, consider what happens to the Id property when you create the following instances.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;MyGenericClass&amp;lt;object&amp;gt; obj1 = new MyGenericClass&amp;lt;object&amp;gt;(null);&lt;br /&gt;MyGenericClass&amp;lt;object&amp;gt; obj2 = new MyGenericClass&amp;lt;object&amp;gt;(null);&lt;br /&gt;MyGenericClass&amp;lt;string&amp;gt; obj3 = new MyGenericClass&amp;lt;string&amp;gt;(null);&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;The actual values of the Id properties for those objects are.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;obj1.Id == 1&lt;br /&gt;obj2.Id == 2&lt;br /&gt;obj3.Id == 1&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;The reason this occurs is because &lt;code&gt;obj1&lt;/code&gt; and &lt;code&gt;obj2&lt;/code&gt; are of the same type (&lt;code&gt;MyGenericClass&amp;lt;object&amp;gt;&lt;/code&gt;) whereas &lt;code&gt;obj3&lt;/code&gt; is actually of a different type (MyGenericClass&amp;lt;string&amp;gt;).  If you truely need them to share the same set of static member variables, then you need another class that contains the statics.  You can either derive your generic from that other class, or you can have the generic use that other class.  I personally prefer the later because I feel that a class intended to only hold static member variables should be a &lt;code&gt;static class&lt;/code&gt;, but the compiler will not let you derive a non-static class from a static class.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-1988639033416612804?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/06/statics-and-generics.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-7820103285227374301</guid><pubDate>Thu, 19 Jun 2008 22:06:00 +0000</pubDate><atom:updated>2008-06-19T21:02:34.947-04:00</atom:updated><title>Mouse Pointers and Cursors</title><description>We've all seen it, and we all want to do it.  If an application is busy doing something for extended period of time, we want to change the cursor so that the user knows the application is still busy.  But, cursor control can be a bit confusing in C#.NET because there are several ways to control the cursor.  I'll try to sum how cursors behave for WinForms within this post.&lt;br /&gt;&lt;br /&gt;For starters, just to get the terminology straight from a Windows' point of view, the &lt;i&gt;mouse pointer&lt;/i&gt; is the location on the screen that changes as the user moves the mouse, and the &lt;i&gt;cursor&lt;/i&gt; is the graphical image that is drawn with its &lt;i&gt;hot spot&lt;/i&gt; at the mouse pointer.&lt;br /&gt;&lt;br /&gt;In .NET, each cursor image is represented by an instance of the &lt;code&gt;System.Windows.Forms.Cursor&lt;/code&gt; class.  Instances of the &lt;code&gt;Cursor&lt;/code&gt; class can be used to represent the standard Windows cursors, as well as custom-defined cursors (generally compiled into a resource file).&lt;br /&gt;&lt;br /&gt;Instances of &lt;code&gt;Cursor&lt;/code&gt; that represent the standard Windows cursors are available as static properties of the &lt;code&gt;System.Windows.Forms.Cursor&lt;b&gt;s&lt;/b&gt;&lt;/code&gt; class.  For example, &lt;code&gt;Cursors.WaitCursor&lt;/code&gt; returns an instance of a &lt;code&gt;Cursor&lt;/code&gt; that contains information about how to display the "wait cursor" configured in Windows.&lt;br /&gt;&lt;br /&gt;In addition to using instances of the &lt;code&gt;Cursor&lt;/code&gt; class to define what different cursors look like, the &lt;code&gt;Cursor&lt;/code&gt; class also has several static properties that described the currently active cursor.  Most noteably, the &lt;code&gt;Cursor.Current&lt;/code&gt; property sets or gets the &lt;code&gt;Cursor&lt;/code&gt; instance that is currently active, and &lt;code&gt;Cursor.Position&lt;/code&gt; property gets or sets the current location of the mouse pointer.&lt;br /&gt;&lt;br /&gt;These static properties describing the current cursor are a bit interesting when it comes to threaded applications.  No matter what thread you are on, the &lt;code&gt;Cursor.Position&lt;/code&gt; property always gets or sets the Windows mouse pointer position immediately.  But, the &lt;code&gt;Cursor.Current&lt;/code&gt; property does not behave the same way!&lt;br /&gt;&lt;br /&gt;Although you can do it without throwing an exception, getting or setting the &lt;code&gt;Cursor.Current&lt;/code&gt; property form any thread other than the main UI thread is somewhat pointless.  If you get the &lt;code&gt;Cursor.Current&lt;/code&gt; property from a non-UI thread, you will notice that it defaults to &lt;code&gt;Cursors.WaitCursor&lt;/code&gt; even if the actual Windows cursor is something else.  And, if you set the &lt;code&gt;Cursor.Current&lt;/code&gt; property from a non-UI thread the actual Windows cursor will not change.  After doing so, however, calling get from a non-UI thread will return that set value.&lt;br /&gt;&lt;br /&gt;Each WinForms control has a &lt;code&gt;Cursor&lt;/code&gt; property inherited from the &lt;code&gt;System.Windows.Forms.Control&lt;/code&gt; class.  When the mouse pointer is over a control, the Windows cursor is changed to whatever is specified by the &lt;code&gt;Cursor&lt;/code&gt; property of the control, and the &lt;code&gt;Cursor.Current&lt;/code&gt; property is changed to return that cursor as well.&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;Control.Cursor&lt;/code&gt; property is a so-called &lt;i&gt;ambient property&lt;/i&gt;.  That means a control will use its container's cursor as long as it has not been specifically set on the control itself.  For example, if you have a button on a form, then setting the &lt;code&gt;Cursor&lt;/code&gt; property of the form (both in Visual Studio and prgrammatically at run-time) will also change the cursor for the button as long as you have not specifically set the button's &lt;code&gt;Cursor&lt;/code&gt; property.&lt;br /&gt;&lt;br /&gt;Setting the &lt;code&gt;Cursor.Current&lt;/code&gt; property from a non-UI thread may not be useful, but setting it from the main UI thread is a way of temporarily overridding the cursors specified by the &lt;code&gt;Cursor&lt;/code&gt; properties of all controls in the application (or at least those on the same UI thread).  Setting the &lt;code&gt;Cursor.Current&lt;/code&gt; property from the main UI thread changes the Windows cursor immediately and application-globally, but only temporarily.  Once &lt;code&gt;Cursor.Current&lt;/code&gt; is specifically set, it will continue to override the controls' cursors until it is changed to something else, or until the UI thread "catches up" and runs out of messages to process.&lt;br /&gt;&lt;br /&gt;If you know you are going to execute code that will block the main UI thread for a bit, you could set &lt;code&gt;Cursor.Current&lt;/code&gt; before executing that code and not have to worry about setting it back or changing it on every form.  Once the UI starts responding again, the cursor will go back to being whatever is set on the &lt;code&gt;Control.Cursor&lt;/code&gt; property of the control the mouse pointer is over.&lt;br /&gt;&lt;br /&gt;If you know you are going to block the main UI thread fo awhile, you could set the &lt;code&gt;Cursor.Current&lt;/code&gt; to &lt;code&gt;Cursors.WaitCursor&lt;/code&gt;, and Windows would display the wait cursor for the entire application until the main UI thread was no longer busy.  But, ideally we do not want to block the main thread for extended periods of time because non-responsive, partially-painted applications not only look bad but also make users think something is wrong.  So, unless a long-runnning task has to be on the main UI thread (such as when creating a bunch of items for a combo box), most programmers &lt;i&gt;should&lt;/i&gt; choose to do long-running tasks on background threads or in dedicated threads so the main UI thread is not blocked.  But, in such cases, we cannot use &lt;code&gt;Cursor.Current&lt;/code&gt; to display the wait cursor because the cursor would immediately reset to whatever is appropriate for the control the mouse pointer is over because the UI would be responsive.  That's where the &lt;code&gt;UseWaitCursor&lt;/code&gt; properties come in!&lt;br /&gt;&lt;br /&gt;Each WinForms control has a &lt;code&gt;UseWaitCursor&lt;/code&gt; property inherited from &lt;code&gt;System.Windows.Forms.Control&lt;/code&gt;.  When this property is true, the wait cursor is used instead of whatever cursor is specified in the &lt;code&gt;Control.Cursor&lt;/code&gt; property whenever the mouse pointer is over the control or any of it's child controls.&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;System.Windows.Forms.Application&lt;/code&gt; class also has a &lt;code&gt;UseWaitCursor&lt;/code&gt; property.  Setting &lt;code&gt;Application.UseWaitCursor&lt;/code&gt; causes the framework to loop over all of the open forms and set the &lt;code&gt;Control.UseWaitCursor&lt;/code&gt; properties on all of those forms.&lt;br /&gt;&lt;br /&gt;There are a few last subtle point to note...&lt;br /&gt;&lt;br /&gt;Unlike the &lt;code&gt;Cursor.Current&lt;/code&gt; property that assumes the main UI thread will be blocked and therefore changes the Windows cursor immediately, setting the &lt;code&gt;Control.UseWaitCursor&lt;/code&gt; or &lt;code&gt;Application.UseWaitCursor&lt;/code&gt; properties assumes the UI will remain responsive and therefore does not change the Windows cursor immediately but instead processes it as any other property change.  Therefore, if you set the &lt;code&gt;UseWaitCursor&lt;/code&gt; and then block the UI thread, you &lt;i&gt;may&lt;/i&gt; never see it!&lt;br /&gt;&lt;br /&gt;Also, if &lt;code&gt;UseWaitCursor&lt;/code&gt; is true, then setting the &lt;code&gt;Cursor.Current&lt;/code&gt; &lt;i&gt;cannot&lt;/i&gt; be used to override the wait cursor.  &lt;br /&gt;&lt;br /&gt;And, using the wait cursor via &lt;code&gt;UseWaitCursor&lt;/code&gt; does not prohibit other mouse events.  It is still possible for the user to press buttons, size forms, enter text, etc. even if &lt;code&gt;UseWaitCursor&lt;/code&gt; is true.&lt;br /&gt;&lt;br /&gt;Finally, there are even more ways to change the cursor, such as via the &lt;code&gt;DragDropEffects&lt;/code&gt;!  (Perhaps I will blog about how they interact with the cursors mentioned above in the future?)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-7820103285227374301?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/06/mouse-pointers-and-cursors.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-8857392757563974522</guid><pubDate>Tue, 20 May 2008 17:36:00 +0000</pubDate><atom:updated>2008-05-20T13:52:26.116-04:00</atom:updated><title>Cannot Multi-Select in File Explorer on Vista</title><description>I was one of the "early adopters" of Vista.  Soon after I installed it, my File Explorer windows started doing two strange things.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;   &lt;li&gt;Putting a little checkbox next to highlighted files or folders&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Multi-select did not work with Ctrl+A, Ctrl+Click or Shift+Click&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;The chekbox thing was not that big of a deal; it was more of a visual annoyance.  I found out later that the checkboxes could be turned on or off via configuration.&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;   &lt;li&gt;Open File Explorer&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Pull down the &lt;i&gt;Tools&lt;/i&gt; menu&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Select &lt;i&gt;Folder Options...&lt;/i&gt;&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Select the &lt;i&gt;View&lt;/i&gt; tab&lt;/li&gt;&lt;br /&gt;   &lt;li&gt;Uncheck the &lt;i&gt;Use check boxes to select items&lt;/i&gt; option&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;The inability to multi-select, however, is a huge burden on the usefullness of the operating system itself.  I had tried several suggestions from various blog postings and message boards, but none of them seemed to work.  Finally, I stumbled across a post that had a "fix" that worked on my machine.  If you have problem with multi-select in Windows Vista, &lt;i&gt;&lt;b&gt;delete&lt;/b&gt; the following two registry keys and then &lt;b&gt;reboot&lt;/b&gt; your computer.&lt;/i&gt;:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\BagMRU&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags&lt;/code&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-8857392757563974522?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/05/cannot-multi-select-in-file-explorer-on.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-6093292134570967615</guid><pubDate>Fri, 11 Apr 2008 15:51:00 +0000</pubDate><atom:updated>2008-04-11T12:58:48.081-04:00</atom:updated><title>Calling an instance method from outside the class before the constructor completes</title><description>If I asked the question "Can you call an instance method on an object before the constructor completes?", most programmers would think about it for awhile and then likely conclude "Sure, I do it all the time.  It is very common to have the constructor itself call an instance method."&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;class MyClass&lt;br /&gt;{&lt;br /&gt;    MyClass()&lt;br /&gt;    {&lt;br /&gt;        MyMethod();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    void MyMethod()&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;But, what if I change the question a bit: "Can you call an instance method on an object &lt;i&gt;from outside the class&lt;/i&gt; before the constructor completes?".  What would your answer be then?  I am guessing that most programmers may assume that cannot happen.  If you assume that cannot happen, then "you assume to much" (stealing a line from Padme).&lt;br /&gt;&lt;br /&gt;I suspect many readers of this posting are now thinking "Huh?", "What?" and "How could you do that?".  How do you call a method from outside the class before the constructor has completed?  In the typical usage, the constructor would always complete before calling a method from outside the class:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;SomeClass someClass = new SomeClass();&lt;br /&gt;someClass.SomeMethod();&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;But, things are not always typical, especially as programs move more asynchronous in nature.  Although it is probably not desirable for code outside of a class to call an instance method on an object before its constructor has completed, there is a very really danger that this can happen!  Consider, for example, the following two classes.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;public class Class1&lt;br /&gt;{&lt;br /&gt;    private object _someObject;&lt;br /&gt;&lt;br /&gt;    public Class1()&lt;br /&gt;    {&lt;br /&gt;        Class2 class2 = Class2.Instance;&lt;br /&gt;        class2.SomeEvent += new EventHandler(Class2_SomeEvent);&lt;br /&gt;        class2.Go();&lt;br /&gt;&lt;br /&gt;        System.Threading.Thread.Sleep(5000);&lt;br /&gt;        _someObject = new object();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void Class2_SomeEvent(&lt;br /&gt;        object sender,&lt;br /&gt;        EventArgs e)&lt;br /&gt;    {&lt;br /&gt;            Type type = _someObject.GetType();&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class Class2&lt;br /&gt;{&lt;br /&gt;    private static Class2 _instance = new Class2();&lt;br /&gt;&lt;br /&gt;    public event EventHandler SomeEvent;&lt;br /&gt;&lt;br /&gt;    private Class2()&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static Class2 Instance&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            return _instance;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void Go()&lt;br /&gt;    {&lt;br /&gt;        MethodInvoker del = new MethodInvoker(DoSomething);&lt;br /&gt;        del.BeginInvoke(new AsyncCallback(DoSomething_Completed), null);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void DoSomething()&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void DoSomething_Completed(IAsyncResult ar)&lt;br /&gt;    {&lt;br /&gt;        OnSomeEvent();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void OnSomeEvent()&lt;br /&gt;    {&lt;br /&gt;        if (SomeEvent == null)&lt;br /&gt;        {&lt;br /&gt;            return;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        try&lt;br /&gt;        {&lt;br /&gt;            SomeEvent(this, new EventArgs() );&lt;br /&gt;        }&lt;br /&gt;        catch(NullReferenceException ex)&lt;br /&gt;        {&lt;br /&gt;            Debug.Assert(false, "The Class1 constructor has not completed yet!");&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;In this example, &lt;code&gt;Class2&lt;/code&gt; is a very simple singleton that provides a &lt;code&gt;Go()&lt;/code&gt; method, and a &lt;code&gt;SomeEvent&lt;/code&gt; event.  The constructor for &lt;code&gt;Class1&lt;/code&gt; registers for the event.  And, for simplicity of this example, the &lt;code&gt;Class1&lt;/code&gt; constructor is also calling the &lt;code&gt;Go()&lt;/code&gt; method, but it could potentially be called by other code outside of both &lt;code&gt;Class1&lt;/code&gt; and &lt;code&gt;Class2&lt;/code&gt;.  Also, note that I have intentionally added a &lt;code&gt;Sleep()&lt;/code&gt; to the example to ensure that you see the problem.&lt;br /&gt;&lt;br /&gt;So, there you have it.  If you run the code above, you will get an assert because &lt;code&gt;_someObject&lt;/code&gt; is null when the &lt;code&gt;Class1.Class2_SomeEvent()&lt;/code&gt; event handler is called even though &lt;code&gt;_someObject&lt;/code&gt; is explicitly set in the &lt;code&gt;Class1&lt;/code&gt; constructor.&lt;br /&gt;&lt;br /&gt;If, from within a class constructor, you register for event handlers or pass delegates into asynchronous methods as callbacks, there exists a possibility that your event handler or callback may get invoked before the constructor has completed.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-6093292134570967615?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/04/calling-instance-method-from-outside.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-3778081689935668998</guid><pubDate>Fri, 21 Mar 2008 21:02:00 +0000</pubDate><atom:updated>2008-03-21T17:46:37.753-04:00</atom:updated><title>More on Control.BeginInvoke()</title><description>By now, everyone knows you use Control.BeginInvoke() to asynchronously execute a delegate on a the main UI thread, right?  But, what happens if you call Control.BeginInvoke() while already on the UI thread?&lt;br /&gt;&lt;br /&gt;The answer is simple: it does the same thing -- it asynchronously invokes the delegate on the main UI thread.&lt;br /&gt;&lt;br /&gt;Huh?  What does that mean if you are already on the UI thread?&lt;br /&gt;&lt;br /&gt;If you are already on the UI thread, you can use Control.BeginInvoke() to queue a delegate to be executed on the main UI thread.  It is added to the end of everything else that is already queue to be processed on the UI thread.  For example, consider the example below.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;private void Button_Click(&lt;br /&gt;   object sender,&lt;br /&gt;   EventArgs e)&lt;br /&gt;{&lt;br /&gt;   _label.Text = "1";&lt;br /&gt;   BeginInvoke( new MethodInvoker( delegate() { _label.Text = "2"; } ));&lt;br /&gt;   _label.Text = "3";&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;What would you expect &lt;code&gt;_label.Text&lt;/code&gt; to be?  After setting it to &lt;code&gt;"1"&lt;/code&gt; its value is &lt;code&gt;"1"&lt;/code&gt;.  After the &lt;code&gt;BeginInvoke()&lt;/code&gt; its value is still &lt;code&gt;"1"&lt;/code&gt;.  After setting it to &lt;code&gt;"3"&lt;/code&gt; it's value is &lt;code&gt;"3"&lt;/code&gt;.  Sometime after &lt;code&gt;Button_Click&lt;/code&gt; has returned, the anonymous method will run and &lt;code&gt;_label.Text&lt;/code&gt; will change to &lt;code&gt;"2"&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;So are there really any reasons why you would want to use this?  Sure, but I don't have time to get into that now.  Perhaps I will post about them in the future.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-3778081689935668998?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/03/more-on-controlbegininvoke.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-3138040594360185878</guid><pubDate>Thu, 20 Mar 2008 22:01:00 +0000</pubDate><atom:updated>2008-03-20T18:03:23.795-04:00</atom:updated><title>TimL on C#.NET has moved!</title><description>I have successfully moved &lt;code&gt;http://csharp.timl.net&lt;/code&gt; to &lt;code&gt;http://timl.net&lt;/code&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-3138040594360185878?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/03/timl-on-cnet-has-moved.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-1634880096094211078</guid><pubDate>Wed, 19 Mar 2008 21:10:00 +0000</pubDate><atom:updated>2008-03-19T17:28:38.445-04:00</atom:updated><title>TimL on C#.NET is moving!</title><description>Sometime over the next few days, I will be moving my C# blog from &lt;code&gt;http://csharp.timl.net&lt;/code&gt; to simply &lt;code&gt;http://timl.net&lt;/code&gt;.  I don't know for sure if it will affect anybody that subscribes to the feed, but I don't think it will.  Never-the-less, I just thought I'd post this message incase any readers run into problems.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-1634880096094211078?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/03/timl-on-cnet-is-moving.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-4528480797011774101</guid><pubDate>Fri, 15 Feb 2008 22:25:00 +0000</pubDate><atom:updated>2008-02-15T18:16:14.920-05:00</atom:updated><title>Are reads and writes of reference type variables atomic?</title><description>This question came up at work today:&lt;br /&gt;&lt;br /&gt;&lt;i&gt;If you have a class that has a getter and setter for a property that is a reference type (such as a user defined class) and that property will be accessed by multiple threads, do you have to protect access to getting or setting the underlying member variable?&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;Bascially, the other developer was asking if he had to do the following:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;class MyClass1&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class MyClass2&lt;br /&gt;{&lt;br /&gt;    object _syncLock = new object();&lt;br /&gt;&lt;br /&gt;    MyClass1 _myClass1;&lt;br /&gt;&lt;br /&gt;    MyClass1 Value&lt;br /&gt;    {&lt;br /&gt;        get&lt;br /&gt;        {&lt;br /&gt;            lock(_syncLock)&lt;br /&gt;            {&lt;br /&gt;                return _myClass1;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        set&lt;br /&gt;        {&lt;br /&gt;            lock(_syncLock)&lt;br /&gt;            {&lt;br /&gt;                _myClass1 = value;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;My answer was "I never do".  But, I soon as a paniced feeling as I started to second-guess myself.  Do I need to do that?  Had I been doing it wrong in everything .NET app I have ever written?&lt;br /&gt;&lt;br /&gt;After thinking about it for awhile, I came to conclusion that setting and getting a reference variable &lt;i&gt;has&lt;/i&gt; to be an atomic operation.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;object a = new object();&lt;br /&gt;object b;&lt;br /&gt;b = a;  // This line must be atomic!&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;If it was not, I reasoned, then the &lt;code&gt;lock(&lt;reference type&gt;)&lt;/code&gt; statement we all love could not possibly be used to protect access to anything because the object referred to by the reference variable that is passed into &lt;code&gt;lock&lt;/code&gt; could be changed by another thread as it was in-process of being assigned as the lock object for the &lt;code&gt;Monitor&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;After to coming to this conclusion, I went to ECMA-334 to see if it had a concrete statement of what I had just determined must be.  Sure enough, section 12.5 Atomicity of Variable References states:&lt;br /&gt;&lt;br /&gt;&lt;i&gt;Reads and writes of the following data types shall be atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and &lt;b&gt;reference types&lt;/b&gt;. In addition, reads and writes of enum types with an underlying type in the previous list shall also be atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, need not be atomic. Aside from the library functions designed for that purpose, there is no guarantee of atomic read-modify-write, such as in the case of increment or decrement.&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;Ok, case closed.  But this also implies something else.  This means that there is an upper limit of the number of objects that can exist in .NET at any one time.  Assuming that each instance of an object is assigned a unique "reference" number, that number is probably 32-bit since that is the largest number of bits that can natively be copied atomically on a 32-bit system.  This means that the absolute maximum number of objects that can exist in .NET at any point in time is &lt;code&gt;2^32 = 4,294,967,296&lt;/code&gt;.  Assuming that each of those objects took only 4-bytes to store its unique 32-bit number and nothing else, that would be &lt;code&gt;2^32 * 4 = 17,179,869,184 bytes (16GB)&lt;/code&gt; of memory to create every possible instance of simple &lt;code&gt;object&lt;/code&gt;s, so I don't think we're going to run out anytime soon.  Although, I can recall when 640K was considered to be 10x the amount of RAM a PC would ever need.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-4528480797011774101?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/02/are-reads-and-writes-of-reference-type.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-6059435215477995747.post-772951201505887873</guid><pubDate>Sat, 09 Feb 2008 07:24:00 +0000</pubDate><atom:updated>2008-02-09T02:25:47.048-05:00</atom:updated><title>Unable to cast object of type 'Y' to type 'Z'</title><description>The other day, I had a very strange exception.  I had an object that very clearly implemented an interface.  Yet, when I tried to cast the object to the interface using &lt;code&gt;as&lt;/code&gt;, the cast &lt;i&gt;always&lt;/i&gt; returned null.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;interface IMyInterface&lt;br /&gt;{&lt;br /&gt;   void MyMethod();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class MyClass : IMyInterface&lt;br /&gt;{&lt;br /&gt;    void MyMethod()&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;MyClass myClass = new MyClass();&lt;br /&gt;IMyInterface myInterface = myClass as IMyInterface();&lt;br /&gt;&lt;br /&gt;if (myInterface == null)&lt;br /&gt;{&lt;br /&gt;    Debug.Assert(false, "What the heck?);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;br /&gt;&lt;br /&gt;Since my application uses interfaces extensively, this seemed like a break-down in the very fabric of the .NET space-time continuum.  All of the other casts of objects to interfaces were working fine, except for this one object.  If there's one thing my years of enigneering and computer programming has taught me, it's that &lt;i&gt;there is always a reason why something really weird happened&lt;/i&gt;.&lt;br /&gt;&lt;br /&gt;I tried everything, and even verified that the object instance did indeed support the interface by using &lt;code&gt;.GetType().GetInterface()&lt;/code&gt; and &lt;code&gt;.GetType().GetInterfaces()&lt;/code&gt;.  Since casts using &lt;code&gt;as&lt;/code&gt; "fail gracefully" and return null, I tried casting using &lt;code&gt;(IMyInterface)&lt;/code&gt; instead to see if I could get an exception. Sure enough, I got an exception:&lt;br /&gt;&lt;br /&gt;"The type initializer for '&lt;i&gt;X&lt;/i&gt;' threw an exception. Unable to cast object of type '&lt;i&gt;Y&lt;/i&gt;' to type '&lt;i&gt;Z&lt;/i&gt;'"&lt;br /&gt;&lt;br /&gt;This "type initializer" exception did, of course, clue me in that there was assembly version issue.  But where?  I double-checked all of our make files (we build at the command line instead of in Visual Studio), deleted all DLLs to make sure there was not some kind of circular reference of the assemblies, closed Visual Studio and all other apps to make sure nothing was keeping a file locked, rebooted the computer, etc.  I spent hours trying to figure out what was happening.  Then, by accident, I started the release version of our software instead of the bug version, and it worked!&lt;br /&gt;&lt;br /&gt;That was new information -- it works in release mode by not in debug mode.  Our build process generates two separate sets of binaries: release and debug.  And, the filenames for the debug binaries all end in the letter "D".&lt;br /&gt;&lt;br /&gt;With this new information, I was eventually able to find the culprit.  Although the application is a WinForms app, it uses &lt;code&gt;XamlReader&lt;/code&gt; and &lt;code&gt;XamlWriter&lt;/code&gt; to serialize and deseialize some custom WPF objects that get displayed in an &lt;code&gt;ElementHost&lt;/code&gt; control.  And, in the assembly that contained our custom controls, I had accidentally omitted the &lt;code&gt;XmlnsDefinition&lt;/code&gt; assembly attribute that maps an XML namespace to a .NET namespace.  As a result, the &lt;code&gt;XamlWriter&lt;/code&gt; was putting the assembly name into the XAML file.&lt;br /&gt;&lt;br /&gt;Since our debug assemblies end in "D" but the release assemblies do not, the XAML files that were generated from release software could only be loaded in release software, and files generated by debug software could only be loaded by debug software.  It just so happes that, during my hours of frustration, I was using the debug version of our software but trying to load XAML files that had apparently been created from our release version.&lt;br /&gt;&lt;br /&gt;Once I found the problem, the solution was simple:  adding the &lt;code&gt;XmlnsDefinition&lt;/code&gt; made the problem go away because the XML namespace was written into the file instead of the assembly.  But, it really got me thinking.  Anytime an assembly is loaded by name, this problem could exist.  For example, the the &lt;code&gt;Type.GetType()&lt;/code&gt; method allows you to load a type from a "type,assembly" string.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;// Create and instance of type MyNameSpace.MyType from assembly MyAssembly&lt;br /&gt;Type myType = Type.GetType("MyNameSpace.MyType,MyAssembly");&lt;br /&gt;MyType myType = (MyType)Activator.CreateInstance(type);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&amp;nbsp;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6059435215477995747-772951201505887873?l=timl.net' alt='' /&gt;&lt;/div&gt;</description><link>http://timl.net/2008/02/unable-to-cast-object-of-type-y-to-type.html</link><author>noreply@blogger.com (TimL)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></item></channel></rss>