Reputation: 29251
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
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
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 int
s 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 int
s 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
Reputation: 837946
Personally I think:
However I don't think Resharper can easily detect the difference between these two situations.
Upvotes: 11