Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always OK to not explicitly initialize a value if you would only be setting it to its default value?

Tags:

c#

Resharper just prompted me on this line of code:

private static bool shouldWriteToDatabase = false;

indicating that I should not say " = false" because bools, apparently, default to false in C#. I've been programming in C# for over a year and a half and never knew that. I guess it just slipped through the cracks, but this leaves me wondering what's good practice.

Do I work on the assumption that default values are understood by all? This would result in cleaner code, but invites ambiguity if another programmer isn't aware of the default value.

like image 654
Sean Anderson Avatar asked Oct 28 '11 17:10

Sean Anderson


3 Answers

Personally I think:

  • It's good to be explicit if your code relies on the intial value.
  • If your code doesn't rely on the initial value, omitting it would make more sense and clutter the code less.

However I don't think Resharper can easily detect the difference between these two situations.

like image 70
Mark Byers Avatar answered Sep 29 '22 08:09

Mark Byers


Am I the only one who thinks that = false; just doesn't clutter the code? As a developer that maintains applications largely written by others, being explicit with what you mean can be very helpful. Yes, bools default to false in C# but when you are looking at someone else's code it can be confusing if this was the intended behavior or if they were just being sloppy.

like image 25
Michael Fox Avatar answered Sep 29 '22 09:09

Michael Fox


Personally, default values are documented just as well as anything else in a language (C#, or any other language). It's straight forward enough that it should be assumed, i.e. an int starts at 0. A scenario that stands out to me is if you want a huge array of ints all holding 0s. Are you going to define that, or just let C# initialize it with 0s?

It seems a little counter-intuitive to assume a large arrays of ints to be 0s, but to have to specify that one bool is false. Specifying the basic variable but not the more complex structure. So I don't initialize anything to it's default value for the sake of consistency.

like image 23
Corey Ogburn Avatar answered Sep 29 '22 07:09

Corey Ogburn