473,473 Members | 2,195 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

try...catch and local variables

I'm getting frustrated with using try...catch with local variables:

The code below wont compile in .NET 1.1: I get the following error: "Use of
unassigned local variable 'oProcessFileReader' "

Is there a way around this error?

<code>
private void Test(string sFileName)
{
StreamReader oProcessFileReader;
try
{
oProcessFileReader = File.OpenText(sFileName);
}
catch (Exception e)
{
MessageBox.Show("Error: "+e.Message);
}
finally
{
if(oProcessFileReader!=null)
oProcessFileReader.Close();
}
}

</code>
--
Thanks
Rick Hodder
Nov 21 '06 #1
28 3799
StreamReader oProcessFileReader=null;

Now it's not unassigned.

Peter
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"RickHodder" wrote:
I'm getting frustrated with using try...catch with local variables:

The code below wont compile in .NET 1.1: I get the following error: "Use of
unassigned local variable 'oProcessFileReader' "

Is there a way around this error?

<code>
private void Test(string sFileName)
{
StreamReader oProcessFileReader;
try
{
oProcessFileReader = File.OpenText(sFileName);
}
catch (Exception e)
{
MessageBox.Show("Error: "+e.Message);
}
finally
{
if(oProcessFileReader!=null)
oProcessFileReader.Close();
}
}

</code>
--
Thanks
Rick Hodder
Nov 21 '06 #2
I'm getting frustrated with using try...catch with local variables:
>
The code below wont compile in .NET 1.1: I get the following error:
"Use of unassigned local variable 'oProcessFileReader' "

Is there a way around this error?
Set oProcessFileReader to null in your catch block.

Best Regards,
Dustin Campbell
Developer Express Inc.
Nov 21 '06 #3
Thanks Peter!

BTW, I really enjoy your blog.
--
Rick Hodder
"Peter Bromberg [C# MVP]" wrote:
StreamReader oProcessFileReader=null;

Now it's not unassigned.

Peter
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"RickHodder" wrote:
I'm getting frustrated with using try...catch with local variables:

The code below wont compile in .NET 1.1: I get the following error: "Use of
unassigned local variable 'oProcessFileReader' "

Is there a way around this error?

<code>
private void Test(string sFileName)
{
StreamReader oProcessFileReader;
try
{
oProcessFileReader = File.OpenText(sFileName);
}
catch (Exception e)
{
MessageBox.Show("Error: "+e.Message);
}
finally
{
if(oProcessFileReader!=null)
oProcessFileReader.Close();
}
}

</code>
--
Thanks
Rick Hodder
Nov 21 '06 #4


"RickHodder" <Ri********@discussions.microsoft.comwrote in message
news:F0**********************************@microsof t.com...
I'm getting frustrated with using try...catch with local variables:

The code below wont compile in .NET 1.1: I get the following error: "Use
of
unassigned local variable 'oProcessFileReader' "

Is there a way around this error?

<code>
private void Test(string sFileName)
{
StreamReader oProcessFileReader;
try
{
oProcessFileReader = File.OpenText(sFileName);
}
catch (Exception e)
{
MessageBox.Show("Error: "+e.Message);
}
finally
{
if(oProcessFileReader!=null)
oProcessFileReader.Close();
}
}

</code>
--
Thanks
Rick Hodder
By just looking at the code and error, I see you are in fact not assigning
oProcessFileReader before using it. Even though you are checking for null,
the compiler isn't smart enough to notice and it results in the error you
are getting. What you can do is simply modify your declaration to read:

StreamReader oProcessFileReader = null;

and it should compile nicely (unless there are other errors in your code
that I'm over-looking.

Note: This is simply a compiler error and I'm not sure if you can turn off
this functionality. It exists to prevent you from doing something more
like:

StreamReader reader;
reader.ReadLine();

Which is obviously bad, so the compiler warns/throws a tantrum when you try
to do something that even remotely resembles this...

HTH,
Mythran
Nov 21 '06 #5
Mythran wrote:
....
Note: This is simply a compiler error and I'm not sure if you can turn
off this functionality. It exists to prevent you from doing something
more like:

StreamReader reader;
reader.ReadLine();

Which is obviously bad, so the compiler warns/throws a tantrum when you
try to do something that even remotely resembles this...
Do you mean that |reader| in your example is null? I am not sure
if memory for local variable declarations is primed with zeros. Is it
somewhere in the language specifications?
Nov 21 '06 #6
I am not sure if memory for local variable
declarations is primed with zeros. Is it
somewhere in the language specifications?
ECMA-334, §12 "A variable shall be definitely assigned (§12.3) before its
value can be obtained."

So within the language, it is irrelevant (an implementation detail) whether
the variable is zero'd - as you cannot legally look to see. The CLR may
behave differently, but since this is a C# NG...

Marc
Nov 21 '06 #7
Marc Gravell wrote:
>I am not sure if memory for local variable
declarations is primed with zeros. Is it
somewhere in the language specifications?

ECMA-334, §12 "A variable shall be definitely assigned (§12.3) before its
value can be obtained."

So within the language, it is irrelevant (an implementation detail) whether
the variable is zero'd - as you cannot legally look to see. The CLR may
behave differently, but since this is a C# NG...
Then, this is not a compiler error, contrary to what was suggested. Thanks.
Nov 21 '06 #8
Another way to write your code would be to use the "using" statement. It is
basically under the hood a try/finally statement which calls the Dispose
method on an object that implement IDisposable. If you want your catch
statement you will have to explicitly put that inside the using statment. So
your code:
private void Test(string sFileName)
{
StreamReader oProcessFileReader;
try
{
oProcessFileReader = File.OpenText(sFileName);
}
catch (Exception e)
{
MessageBox.Show("Error: "+e.Message);
}
finally
{
if(oProcessFileReader!=null)
oProcessFileReader.Close();
}
}
would become (without the catch statement):

private void Test(string sFileName)
{
using(StreamReader oProcessFileReader = File.OpenText(sFileName))
{
//use the oProcessFileReader
}

//here the stream has been disposed.
}

So even if an exception is thrown the resources are cleaned up, like in your
code, but with less typing :-).

Mark.
--
http://www.markdawson.org
"RickHodder" wrote:
I'm getting frustrated with using try...catch with local variables:

The code below wont compile in .NET 1.1: I get the following error: "Use of
unassigned local variable 'oProcessFileReader' "

Is there a way around this error?

<code>
private void Test(string sFileName)
{
StreamReader oProcessFileReader;
try
{
oProcessFileReader = File.OpenText(sFileName);
}
catch (Exception e)
{
MessageBox.Show("Error: "+e.Message);
}
finally
{
if(oProcessFileReader!=null)
oProcessFileReader.Close();
}
}

</code>
--
Thanks
Rick Hodder
Nov 21 '06 #9


"Sericinus hunter" <se*****@flash.netwrote in message
news:#T**************@TK2MSFTNGP02.phx.gbl...
Marc Gravell wrote:
>>I am not sure if memory for local variable
declarations is primed with zeros. Is it
somewhere in the language specifications?

ECMA-334, §12 "A variable shall be definitely assigned (§12.3) before its
value can be obtained."

So within the language, it is irrelevant (an implementation detail)
whether the variable is zero'd - as you cannot legally look to see. The
CLR may behave differently, but since this is a C# NG...

Then, this is not a compiler error, contrary to what was suggested.
Thanks.
My apologies, it should read, "this is a compile* error" not compiler and
disregard the "I'm not sure if you can turn off this functionality", cause
obviously, you can't...

:)

HTH,
Mythran
Nov 21 '06 #10
>I'm getting frustrated with using try...catch with local variables:
>>
The code below wont compile in .NET 1.1: I get the following error:
"Use of unassigned local variable 'oProcessFileReader' "

Is there a way around this error?
Set oProcessFileReader to null in your catch block.
Sorry, I must have been out to lunch when I wrote. Initialize oProcessFileReader
to null when you declare it.

Best Regards,
Dustin Campbell
Developer Express Inc.
Nov 21 '06 #11
Another way to write your code would be to use the "using" statement.
It is basically under the hood a try/finally statement which calls the
Dispose method on an object that implement IDisposable. If you want
your catch statement you will have to explicitly put that inside the
using statment. So your code:
>private void Test(string sFileName)
{
StreamReader oProcessFileReader;
try
{
oProcessFileReader = File.OpenText(sFileName);
}
catch (Exception e)
{
MessageBox.Show("Error: "+e.Message);
}
finally
{
if(oProcessFileReader!=null)
oProcessFileReader.Close();
}
}
would become (without the catch statement):

private void Test(string sFileName)
{
using(StreamReader oProcessFileReader = File.OpenText(sFileName))
{
//use the oProcessFileReader
}
//here the stream has been disposed.
}
So even if an exception is thrown the resources are cleaned up, like
in your code, but with less typing :-).
Unfortunately, a using statement doesn't actually protect the code that was
protected before. It will compile to this:

StreamReader oProcessFileReader = File.OpenText(sFileName);
try
{
// use the oProcessFileReader
}
finally
{
if (oProcessFileReader != null)
((IDisposable)oProcessFileReader).Dispose();
}

So, if an exception is raised by File.OpenText(), the call stack will immediately
unwind and the try/finally code doesn't ever execute. IOW, the code that
you presented doesn't actually do the same thing. I suppose that you *could*
do this:

private void Test(string sFileName)
{
try
{
using (StreamReader oProcessFileReader = File.OpenText(sFileName))
{
//use the oProcessFileReader
}

//here the stream has been disposed.
}
catch (Exception e)
{
MessageBox.Show("Error: " + e.Message);
}
}

But, now the scope for try/catch is pretty different--it will also be catching
any exceptions thrown by code other than File.OpenText.

I don't think there's anyway to precisely re-write the original code with
a using statement.

Best Regards,
Dustin Campbell
Developer Express Inc.
Nov 21 '06 #12
You're welcome, thanks for the compliment. Isn't it fun to see how 10 people
all say the same thing!
Peter
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"RickHodder" wrote:
Thanks Peter!

BTW, I really enjoy your blog.
--
Rick Hodder
"Peter Bromberg [C# MVP]" wrote:
StreamReader oProcessFileReader=null;

Now it's not unassigned.

Peter
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"RickHodder" wrote:
I'm getting frustrated with using try...catch with local variables:
>
The code below wont compile in .NET 1.1: I get the following error: "Use of
unassigned local variable 'oProcessFileReader' "
>
Is there a way around this error?
>
<code>
private void Test(string sFileName)
{
StreamReader oProcessFileReader;
try
{
oProcessFileReader = File.OpenText(sFileName);
}
catch (Exception e)
{
MessageBox.Show("Error: "+e.Message);
}
finally
{
if(oProcessFileReader!=null)
oProcessFileReader.Close();
}
}
>
</code>
>
>
--
Thanks
Rick Hodder
Nov 21 '06 #13
You are correct, I should have looked more closely at the OP. Note to self,
do not post when running out the door :-)
Unfortunately, a using statement doesn't actually protect the code that was
protected before. It will compile to this:

StreamReader oProcessFileReader = File.OpenText(sFileName);
try
{
// use the oProcessFileReader
}
finally
{
if (oProcessFileReader != null)
((IDisposable)oProcessFileReader).Dispose();
}
Also there are two extra braces that get compiled by the using statement to
limit the scope the of the local variable:

{
StreamReader oProcessFileReader = File.OpenText(sFileName);
try
{
// use the oProcessFileReader
}
finally
{
if (oProcessFileReader != null)
((IDisposable)oProcessFileReader).Dispose();
}
}

Mark.
--
http://www.markdawson.org
"Dustin Campbell" wrote:
Another way to write your code would be to use the "using" statement.
It is basically under the hood a try/finally statement which calls the
Dispose method on an object that implement IDisposable. If you want
your catch statement you will have to explicitly put that inside the
using statment. So your code:
private void Test(string sFileName)
{
StreamReader oProcessFileReader;
try
{
oProcessFileReader = File.OpenText(sFileName);
}
catch (Exception e)
{
MessageBox.Show("Error: "+e.Message);
}
finally
{
if(oProcessFileReader!=null)
oProcessFileReader.Close();
}
}
would become (without the catch statement):

private void Test(string sFileName)
{
using(StreamReader oProcessFileReader = File.OpenText(sFileName))
{
//use the oProcessFileReader
}
//here the stream has been disposed.
}
So even if an exception is thrown the resources are cleaned up, like
in your code, but with less typing :-).

Unfortunately, a using statement doesn't actually protect the code that was
protected before. It will compile to this:

StreamReader oProcessFileReader = File.OpenText(sFileName);
try
{
// use the oProcessFileReader
}
finally
{
if (oProcessFileReader != null)
((IDisposable)oProcessFileReader).Dispose();
}

So, if an exception is raised by File.OpenText(), the call stack will immediately
unwind and the try/finally code doesn't ever execute. IOW, the code that
you presented doesn't actually do the same thing. I suppose that you *could*
do this:

private void Test(string sFileName)
{
try
{
using (StreamReader oProcessFileReader = File.OpenText(sFileName))
{
//use the oProcessFileReader
}

//here the stream has been disposed.
}
catch (Exception e)
{
MessageBox.Show("Error: " + e.Message);
}
}

But, now the scope for try/catch is pretty different--it will also be catching
any exceptions thrown by code other than File.OpenText.

I don't think there's anyway to precisely re-write the original code with
a using statement.

Best Regards,
Dustin Campbell
Developer Express Inc.
Nov 21 '06 #14
"Mythran" <ki********@hotmail.comwrote in message
news:uZ**************@TK2MSFTNGP02.phx.gbl...
By just looking at the code and error, I see you are in fact not assigning
oProcessFileReader before using it. Even though you are checking for
null, the compiler isn't smart enough to notice and it results in the
error you are getting.
The compiler does notice that he's checking for null. The problem is that
he's not allowed to check for null until he's set the variable to null. He
really does have an uninitialized variable bug in his code.
[...]
Note: This is simply a compiler error and I'm not sure if you can turn
off this functionality. It exists to prevent you from doing something
more like:

StreamReader reader;
reader.ReadLine();

Which is obviously bad, so the compiler warns/throws a tantrum when you
try to do something that even remotely resembles this...
In this particular case, there *is* a code path that can result in the local
variable being accessed before being initialized, without initialization in
the declaration. Initializing the local variable is indeed the correct
solution to the error, and is also correct relative to the rest of the code
that was posted.

However, unfortunately the compiler sometimes also incorrectly complains
that the variable is uninitialized, even when all code paths *do* initialize
the variable before it's accessed.

IMHO, this is a serious compiler bug, because the only way to get rid of the
error is to put in a "dummy" initialization (such as setting the variable to
null), which consequentially will hide any true "uninitialized variable"
errors in the code.

In other words, with the compiler in the state in which it is now, there are
actually situations in which the compiler forces the programmer to write
code that is *more* likely to contain the bug that the error is trying to
help avoid. I'd find the irony very entertaining, if it weren't for the
fact that there's a serious code quality issue related to it. :)

Pete
Nov 21 '06 #15
Hi Dustin,

This is just for the fun of it, but I think your code:

try
{
using (StreamReader oProcessFileReader = File.OpenText(sFileName))
{ //use the oProcessFileReader
}

//here the stream has been disposed.
}
catch (Exception e)
{
MessageBox.Show("Error: " + e.Message);
}

is very similar in functionality to the original code. (with some scope
issues aside, because oProcessFileReader is not accessible now outside
the using block)
>But, now the scope for try/catch is pretty different--it will also be
catching any exceptions thrown by code other than File.OpenText.
On the original code, as it was inside a try/catch/finally block (and I
am still not sure what try/catch/finally blocks are useful for), if he
wanted to do anything with the stream, it would also catch those
exceptions, as your code does:

StreamReader oProcessFileReader = null;
try
{
oProcessFileReader = File.OpenText(sFileName);
//Do whatever you want to do with the stream here.
//Note that an exception here will be processed on the
//catch statement.
}
catch (Exception e)
{
MessageBox.Show("Error: "+e.Message);
}
finally
{
if(oProcessFileReader!=null)
oProcessFileReader.Close();
}
Regards,
Adrian.
Nov 21 '06 #16


"Peter Duniho" <Np*********@NnOwSlPiAnMk.comwrote in message
news:12*************@corp.supernews.com...
"Mythran" <ki********@hotmail.comwrote in message
news:uZ**************@TK2MSFTNGP02.phx.gbl...
>By just looking at the code and error, I see you are in fact not
assigning oProcessFileReader before using it. Even though you are
checking for null, the compiler isn't smart enough to notice and it
results in the error you are getting.

The compiler does notice that he's checking for null. The problem is that
he's not allowed to check for null until he's set the variable to null.
He really does have an uninitialized variable bug in his code.
>[...]
Note: This is simply a compiler error and I'm not sure if you can turn
off this functionality. It exists to prevent you from doing something
more like:

StreamReader reader;
reader.ReadLine();

Which is obviously bad, so the compiler warns/throws a tantrum when you
try to do something that even remotely resembles this...

In this particular case, there *is* a code path that can result in the
local variable being accessed before being initialized, without
initialization in the declaration. Initializing the local variable is
indeed the correct solution to the error, and is also correct relative to
the rest of the code that was posted.

However, unfortunately the compiler sometimes also incorrectly complains
that the variable is uninitialized, even when all code paths *do*
initialize the variable before it's accessed.

IMHO, this is a serious compiler bug, because the only way to get rid of
the error is to put in a "dummy" initialization (such as setting the
variable to null), which consequentially will hide any true "uninitialized
variable" errors in the code.

In other words, with the compiler in the state in which it is now, there
are actually situations in which the compiler forces the programmer to
write code that is *more* likely to contain the bug that the error is
trying to help avoid. I'd find the irony very entertaining, if it weren't
for the fact that there's a serious code quality issue related to it. :)

Pete
Yes yes, what I was thinking and what I typed were two diff things...

The compiler/framework isn't smart enough to see that it's just checking to
see that it's null...not really "smart enough", but wasn't written to work
that way :)

I wonder, and it's not tested...

StreamReader sr;
if (true) { sr = ... }
if (sr == null) { ... }

I wonder if the compiler/framework will barf on that too? :) Most
likely...

Maybe
HTH,
Mythran
Nov 22 '06 #17
"Mythran" <ki********@hotmail.comwrote in message
news:%2****************@TK2MSFTNGP02.phx.gbl...
Yes yes, what I was thinking and what I typed were two diff things...
Is that still happening. :)
The compiler/framework isn't smart enough to see that it's just checking
to see that it's null
Checking to see that a variable is null is *accessing* that variable. If
the variable has not been initialized, then checking for null (or any other
value) is illegal.

This isn't an issue of "smart enough". The error in this case is valid and
correct. The code *is* actually buggy, as the variable is being used at a
point in time at which it's undefined.
...not really "smart enough", but wasn't written to work that way :)
In this particular example, the compiler is doing exactly what it's supposed
to.
I wonder, and it's not tested...

StreamReader sr;
if (true) { sr = ... }
if (sr == null) { ... }

I wonder if the compiler/framework will barf on that too? :) Most
likely...
That is more like the compiler bug I was talking about. I haven't tried
that exact construct, but I have written code where it is provable that the
variable *is* initialized prior to access, and yet the compiler complains
that it isn't. In these cases (such as your example, and the other examples
I've seen), adding the initialization required to get the compiler to stop
complaining can actually result in what is effectively an uninitialized
value bug, because the otherwise-unnecessary initialization hides any other
problems with initialization.

Pete
Nov 22 '06 #18
On Tue, 21 Nov 2006 10:23:02 -0800, Peter Bromberg [C# MVP]
<pb*******@yahoo.nospammin.comwrote:
>You're welcome, thanks for the compliment. Isn't it fun to see how 10 people
all say the same thing!
Peter
Amusing... (Your second sentence and all the answers) ;o)

Brevity is next to godliness....

Good luck with your project,

Otis Mukinfus
http://www.arltex.com
http://www.tomchilders.com
Nov 22 '06 #19
Peter Duniho <Np*********@NnOwSlPiAnMk.comwrote:

<snip>
I wonder if the compiler/framework will barf on that too? :) Most
likely...

That is more like the compiler bug I was talking about. I haven't tried
that exact construct, but I have written code where it is provable that the
variable *is* initialized prior to access, and yet the compiler complains
that it isn't. In these cases (such as your example, and the other examples
I've seen), adding the initialization required to get the compiler to stop
complaining can actually result in what is effectively an uninitialized
value bug, because the otherwise-unnecessary initialization hides any other
problems with initialization.
It's not a compiler bug. The compiler is working exactly to the
language specification, as it should do.

Now, if you want to complain that the language specification is
"wrong" - the specification is already fairly complicated in terms of
working out precisely when a variable is definitely assigned. I believe
it is much better to make a language slightly "dumber" but simpler to
reason about (i.e. simpler to make sure the compiler is correct,
simpler to make sure the specification doesn't let some oddities
through etc) than to try to make it incredibly smart.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 22 '06 #20
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
It's not a compiler bug. The compiler is working exactly to the
language specification, as it should do.
I don't have a copy of the language specification. Would you please quote
the part you're referencing, where the language specification says that even
if a statement is reachable only by code paths that initialize the variable,
the compiler should still emit an "uninitialized variable" error.

Thanks,
Pete
Nov 22 '06 #21
"Otis Mukinfus" <ph***@emailaddress.comwrote in message
news:j4********************************@4ax.com...
Brevity is next to godliness....
But only in a really bad dictionary... ;-)
Nov 22 '06 #22
Peter Duniho <Np*********@NnOwSlPiAnMk.comwrote:
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
It's not a compiler bug. The compiler is working exactly to the
language specification, as it should do.

I don't have a copy of the language specification. Would you please quote
the part you're referencing, where the language specification says that even
if a statement is reachable only by code paths that initialize the variable,
the compiler should still emit an "uninitialized variable" error.
From the C# 1.1 ECMA spec:

http://www.jaggersoft.com/csharp_standard/12.3.htm
and the pages following (click on the arrows on the right)

(I don't have a public link to a 2.0 spec handy.)

Those rules define the whether or not something is definitely assigned.
They don't say anything about things which the compiler *could* reason
about, such as:

string x;
for (int i=0; i < 10; i++)
{
// 0 < 10 so this will always be executed exactly
// once
x = "value";
}
Console.WriteLine (x);

and

string x;
if (true)
{
// This will definitely be executed
x = "value";
}
Console.WriteLine (x);

However, there *is* enough reasoning (because it has nothing to do with
the expressions within the statements) for this to be okay:

string x;
if (something)
{
x = "value";
}
else
{
x = "othervalue";
}
Console.WriteLine (x);
http://www.jaggersoft.com/csharp_standard/12.htm states that a variable
must be definitely assigned before its value can be obtained.

Any compiler which *did* allow either of the first two snippets above
to be compiled without error would be violating the spec.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Nov 22 '06 #23
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
[...]
Any compiler which *did* allow either of the first two snippets above
to be compiled without error would be violating the spec.
I don't understand why that is the case. The page you referred me to simply
says "a variable is said to be definitely assigned if the compiler can
prove, by static flow analysis, that the variable has been automatically
initialized or has been the target of at least one assignment".

Since it is possible by static flow analysis (that is, by analyzing the flow
of execution in a non-runtime situation) to show that both of the examples
you mention will definitely assign the variable, why is the variable still
considered unassigned?

Pete
Nov 22 '06 #24
It does spell out the official rules in great depth; 12.3.3.9 states
that "for" is treated as "while"; "while" is described in 12.3.3.7:
http://www.jaggersoft.com/csharp_standard/12.3.3.7.htm

This basically gives a few rules about what happens if the loop test
(typically e.g. "i<10" in "for") definitely assigns a variable, but
says nothing about the body. So that is what any compliant compiler
should do...

Marc

Nov 23 '06 #25
"Marc Gravell" <ma**********@gmail.comwrote in message
news:11**********************@m7g2000cwm.googlegro ups.com...
It does spell out the official rules in great depth; 12.3.3.9 states
that "for" is treated as "while"; "while" is described in 12.3.3.7:
http://www.jaggersoft.com/csharp_standard/12.3.3.7.htm

This basically gives a few rules about what happens if the loop test
(typically e.g. "i<10" in "for") definitely assigns a variable, but
says nothing about the body. So that is what any compliant compiler
should do...
Well, I will admit that I have no special insight into the intent of the
writers of the specification. However, my interpretation is that the
specification "says nothing about the body" because the body is itself a
statement, and the rules for that statement would be described elsewhere,
depending on the form it takes.

It's the standard recursive grammar sort of thing.

And in particular, static analysis can show in that situation that the body
statement *is* reached, and *does* initialize the variable.

So, I still don't see anything in the specification that says that even when
a statement is only reachable by code paths that initialize a variable, the
compiler should emit an "uninitialized variable" error.

Pete
Nov 23 '06 #26
"Peter Duniho" <Np*********@NnOwSlPiAnMk.comwrote in message
news:12*************@corp.supernews.com...
And in particular, static analysis can show in that situation that the
body statement *is* reached, and *does* initialize the variable.
Clarification:

"is *always* reached". That is, there is no code path that avoids the body
statement.
Nov 23 '06 #27
Peter Duniho wrote:
Well, I will admit that I have no special insight into the intent of the
writers of the specification. However, my interpretation is that the
specification "says nothing about the body" because the body is itself a
statement, and the rules for that statement would be described elsewhere,
depending on the form it takes.
The rules for definite assignment are all laid out under the section I
pointed you at - but they're not all on one page. That's why I
explained that you should use the arrows on the right of the page to
see the rest of the details.

<snip>
So, I still don't see anything in the specification that says that even when
a statement is only reachable by code paths that initialize a variable, the
compiler should emit an "uninitialized variable" error.
I have to admit to a mistake earlier - section 15.1 of the spec is
relevant here:
http://www.jaggersoft.com/csharp_standard/15.1.htm

In particular:

int x;
if (true)
{
x=0;
}
Console.WriteLine (x);

*is* valid, because the if expression is a *constant* one. The
following is invalid, because the compiler doesn't do any reasoning
about possible values of variables:
int x;
bool y = true;
if (y)
{
x=0;
}
Console.WriteLine (x);

In other words, the compiler does some *very primitive* checking. For
the "if" statement, the rules for reachability are described in
http://www.jaggersoft.com/csharp_standard/15.7.1.htm

Hope this clears things up - apologies for the previous inaccuracy
about the "if" example.

Jon

Nov 23 '06 #28
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
Peter Duniho <Np*********@NnOwSlPiAnMk.comwrote:
>"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft. com...
It's not a compiler bug. The compiler is working exactly to the
language specification, as it should do.

I don't have a copy of the language specification. Would you please quote
the part you're referencing, where the language specification says that even
if a statement is reachable only by code paths that initialize the variable,
the compiler should still emit an "uninitialized variable" error.

From the C# 1.1 ECMA spec:

http://www.jaggersoft.com/csharp_standard/12.3.htm
and the pages following (click on the arrows on the right)

(I don't have a public link to a 2.0 spec handy.)
Here it is:
http://www.ecma-international.org/pu...s/Ecma-334.htm
Willy.

Nov 23 '06 #29

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: ChrisB | last post by:
Hello All: I notice that when using try/catch blocks in C#, variables declared in the try block go out of scope in the finally block. So, for example, the following code generates a compiler...
37
by: clintonG | last post by:
Has somebody written any guidelines regarding how to determine when try-catch blocks should be used and where their use would or could be considered superfluous? <%= Clinton Gallagher...
23
by: VB Programmer | last post by:
Variable scope doesn't make sense to me when it comes to Try Catch Finally. Example: In order to close/dispose a db connection you have to dim the connection outside of the Try Catch Finally...
22
by: STom | last post by:
I heard someone mention to me that the use of try catch exception handling is very expensive (in relative terms of slowing an app down) if it is used frequently. Of course they could not explain...
34
by: Bob | last post by:
Hi, The compiler gives Warning 96 Variable 'cmdSource' is used before it has been assigned a value. A null reference exception could result at runtime. Dim cmdSource as SQlClient.SQLDataReader...
7
by: What-A-Tool | last post by:
In the following code, "catch" is underlined in blue, and the error "the variable fx is declared but never used" is displayed when I mouse hover over it. Am I doing something wrong, or do I just...
7
by: tommaso.gastaldi | last post by:
It would be useful, sometimes, when debugging, to disable all the try /catch one has in the program (clearly not commenting them out). Any info or hint on that? -tom
12
by: reycri | last post by:
While the following is allowed: if (a == b) SomeFunction(); else OtherFunction(); The following is not: try
14
by: Jake K | last post by:
How do I access variables that are set within a try/catch block? The following code produces a use of unassigned local variable error: string varOne; try { //access database here, select,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.