Domanda

All over our codebase, I see stuff like this all the time:

 private bool myBool1 = false;
 private bool myBool2 = false;

What's the point of creating a variable and setting its value to the default, instead of simply just private bool myBool1;?

I have billions of notifications from Resharper saying its redundant :)

È stato utile?

Soluzione

What's the purpose of initializing a variable to its default value?

Nothing, it might be just a practice. It can be clear to newbie who don't know the default value of bool(Of course, he can't be a developer if he doesn't know this).

While resharper is right in saying it is redundant it was even harmful in earlier version of .Net though it is optimized later.

After reading this article only I myself stopped initializing fields to its default value.

Altri suggerimenti

It is not necessarily to do it that way, but rather a "code" policy that is maintained within a production environment. It is explicit that myBool1 is false as default, but it may be considered as a good habit (good as in consequent) to declare your variables to their default values manually.

Try to be consequent in what you are doing in your production environment. If you'd like to be clear and declare all variables to their default values manually, you should - in my opinion - do it everywhere. However, morally I think that manually declaring your variables to their default values is a bad habit, because it only gives your compiler more work to do and it is self-evident that that should be avoided as much as possible.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top