Duplicate question to :
Should I always/ever/never initialize object fields to default values?
Environment: Visual Studio 2008 w/ Resharper 4.1 w/ 32bit .NET Framework 3.5
Resharper reports that
Initializing field by default value is redundant
Is it a bad practice to declare a default field value, explicitly?
I find explicitly declaring default value to be more readable.
By the way this is not a duplication of this question Are default parameters bad practice in OOP?
[UPDATE] For those wondering on where to change Resharper 4.1 setting to change the warning to hint/suggestion; Changing following setting
will change Visual Studio 2008
It is redundant, but I would stay consistent. If you are always initializing fields, keep it that way regardless of the type. Also, as you pointed out in a comment, being required to think about default values for certain types is distracting, so another reason to initialize first.
If you find it more readable that way, that's fine. I don't think it'll affect the JITted code - and even if it does, the performance hit will be absolutely tiny.
If ReSharper is annoying you when it comes to this warning, just configure it not to treat it as a problem. I don't have ReSharper on this machine, but I think it's fairly easy to find the relevant options - let me know if you can't and I'll look for it when I'm on the right machine.
The general answer is like others have stated, if it makes more sense to you and your team then reset the Reshaper setting to a hint. The C# will initialize all values to their default value (0 for numbers, null
for reference types) which is equivalent to the .NET 2.0 default operator:
int i = default(int);
EDIT: You wouldn't use the above in your code. It is equivalent to 'i = 0', however it is much less readable. I only used it to illustrate the point about the unnassigned variables are initialized with their default value.
Initializing the fields might imply a performance penalty:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With