Monday, December 30, 2013

A Common Misconception

I see this pattern a lot, particularly on Stack Overflow but also in some of the apps I'm maintaining.

DataSet ds = new DataSet();
ds = dataLayer.GetExampleData();


I was puzzled as to why the programmer would initialize a variable to a new object instance when the very next step is to set the variable to something else.  The DataSet created in the first line is thrown away and never used.  It seems mildly counter-productive.

But I think I’ve figured it out.  The programmer must have been under the impression that when a variable is set to the result of a method, and that method returns null, the variable retains its previous value. 

That isn’t true.

Let me restate that for emphasis:  THIS ISN’T TRUE.  When you set a value to the result of a method call, your variable is set to whatever that method call returns.  If the method call returns null, your variable is now set to null.   Period.  End of story.

I don’t know a language that works otherwise, although I’m sure (this being a big universe) that there must be one or two that do.   The key point, though, is:  THIS ISN’T HOW C# WORKS. 

4 Comments:

Blogger Rob Janssen said...

It might be because Visual Studio complains about uninitialized variables (although that "complaint" should go away as soon as you assign the method's results to it and the actual correct way to go, ofcourse, is to initialize the variable simply to null).

9/15/2015 3:44 AM  
Blogger Unknown said...

The assertion about variable assignment holds for the given example, but fails with Try/Catch patterns. An exception-throwing assignment function may be ignored with proper scoping.

9/15/2015 5:05 PM  
Blogger Ann said...

Rob: Yes, I think you're probably right.

Unknown: Yes, you're right! In that case, the variable would retain its original value.

9/19/2015 10:43 AM  
Blogger Werner Ebner said...


Asking questions are really nice thing if you are not understanding something totally, but this piece of writing provides nice understanding yet. paypal.com login

4/25/2018 12:17 AM  

Post a Comment

<< Home