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. 

7 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 I Digital Academy said...

It's Really A Post. Looking For Some More Stuff.
Spoken english Training in Bangalore

11/08/2017 7:03 AM  
Blogger Berthold Hanisch said...


Incredible points. Solid arguments. Keep up the good work. pnc bank online banking

11/09/2017 4:55 PM  
Blogger Chaithra L said...

It's Really A Post. Looking For Some More Stuff.
Best Digital Marketing Courses in Bangalore

12/06/2017 6:44 AM  
Blogger Top beauty parlours in Bangalore said...


helpful information, thanks for writing and share this information
freelance adwords specialist

2/12/2018 12:15 AM  

Post a Comment

Links to this post:

Create a Link

<< Home