Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad practice to explicitly declare a default field value? [duplicate]

Tags:

c#

resharper

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

alt text

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 alt text

will change Visual Studio 2008
alt text

like image 448
dance2die Avatar asked Mar 16 '09 17:03

dance2die


4 Answers

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.

like image 142
Ed S. Avatar answered Nov 09 '22 12:11

Ed S.


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.

like image 42
Jon Skeet Avatar answered Nov 09 '22 13:11

Jon Skeet


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.

like image 1
CodeMonkeyKing Avatar answered Nov 09 '22 13:11

CodeMonkeyKing


Initializing the fields might imply a performance penalty:

  • http://www.codeproject.com/KB/dotnet/DontInitializeVariables.aspx
  • http://blog.codinghorror.com/for-best-results-dont-initialize-variables/
like image 2
kjv Avatar answered Nov 09 '22 13:11

kjv