Sean Anderson
Sean Anderson

Reputation: 29251

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

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.

Upvotes: 11

Views: 654

Answers (3)

Michael Fox
Michael Fox

Reputation: 611

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.

Upvotes: 4

Corey Ogburn
Corey Ogburn

Reputation: 24717

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.

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 837946

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.

Upvotes: 11

Related Questions