>>> It is possible to declare and use/instantiate a class with a
>>> uninitialized readonly field without even a compiler warning. Why don't I
[quoted text clipped - 14 lines]
> With C#, you'd typically get a warning alow the lines of "variable xyz is
> never written and will always have its default value null".
That's not a warning saying that the variable is uninitialized. It's
saying that it _is_ initialized, to the default value.
It's true, I should have read the original post more carefully. The
author seems to be saying that NO warning is provided, while I
interpreted it as saying that there's no warning about the uninitialized
variable.
There definitely is a warning, assuming the read-only field is not
explicitly assigned anywhere. It's just not saying that the variable is
uninitialized.
IMHO, the OP confuses the issue by including the second scenario, which
has even more reason for not generating any warning. But certainly even
in that case too, a warning about an uninitialized variable is unwarranted.
> Or is it assigned in some constructors and not others?
Having a constructor that initializes a readonly field will suppress the
"default value" warning, yes. After all, the warning is simply saying
that there's _no_ way for the field to be anything other than the
default value. The lack of a warning doesn't mean that the field will
_always_ be something other than the default value.
But the warning is talking about the value that _is_ used to initialize
the field, not whether the field is initialized at all.
Perhaps this is the case the OP is running into in which _no_ warnings
are produced. But even if a warning is produced, it won't be one that
mentions an uninitialized field.
Pete
cody - 08 Oct 2007 21:07 GMT
>>>> It is possible to declare and use/instantiate a class with a
>>>> uninitialized readonly field without even a compiler warning. Why
[quoted text clipped - 47 lines]
>
> Pete
My problem is that there is *no* warning at all, even if it is
guaranteed that the variable is never assigned to in the program:
public class B
{
public readonly int a;
}
static void Main()
{
B b = new B();
int i = b.a;
}
It also doesn't matter whether the class is sealed or not or whether it
has an internal constructor. There is *no* warning - unless "a" itself
is declared internal or private in which case a warning is generated
that "a is never assigned to..".