Instance vs Local Initialization

V

vooose

Consider

{
bool var;
if(var)
Console.WriteLine("var is true");
}

results in the compilation error

Use of unassigned local variable 'var'

If you make var an instance variable you don't get a compile error as
the variable is effectively 'initialized' to all zeros. Why can't local
variables behave in this manner?

It irritates me that I have to type

bool var=false;

Regards
 
J

Jon Skeet [C# MVP]

vooose said:
Consider

{
bool var;
if(var)
Console.WriteLine("var is true");
}

results in the compilation error

Use of unassigned local variable 'var'

If you make var an instance variable you don't get a compile error as
the variable is effectively 'initialized' to all zeros. Why can't local
variables behave in this manner?

They could - but it's better that they don't. In a way, the *downside*
is that you *can't* do this with instance variables.

The fact that you can't accidentally use a local variable before it's
been initialised is great IMO. I've seen plenty of bugs in C code which
does just that.
It irritates me that I have to type

bool var=false;

If you want to just not execute some code, don't include it in the
first place, or write:

if (false)

It's relatively rare that I find I have to initialise a local variable
with a value which isn't actually useful.
 
V

vooose

Thanks for your reply John. How about this case...

{
bool found=false;
foreach(string temp in arr)
{
if(temp == "hullo")
found=true;
}

if(!found)
//do not found stuff
}

I don't want to initialize found in this case (granted this isnt a big
deal but still...)
 
V

vooose

Sorry Jon for name typo in previous. One more thing...I didn't
understand what you meant by

If you want to just not execute some code, don't include it in the
first place, or write:

if (false)

with respect to my initial question. I would prefer a compilation
error for objects but not for primitives.

Regards
 
J

Jon Skeet [C# MVP]

vooose said:
Thanks for your reply John. How about this case...

{
bool found=false;
foreach(string temp in arr)
{
if(temp == "hullo")
found=true;
}

if(!found)
//do not found stuff
}

I don't want to initialize found in this case (granted this isnt a big
deal but still...)

Why not? It makes it more explicit what you want - which is actually to
be initialised to false.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top