Re: Should I explicitly initialize all member variables?



Jeff Louie <jeff_louie@xxxxxxxxx> wrote:
> Javamman.. The following two lines of code are NOT equivalent in C#.
>
> >MyClass m = null; // redundant
> MyClass m; // better?<
>
> The second line simply creates an unitialized variable. It does not
> default to null.

Yes it does - if it's a member variable. If it's a *local* variable it
remains uninitialised, but the subject line makes it clear that the
question is about member variables. From the spec, section 12.2 (ECMA
numbering):

<quote>
The following categories of variables are automatically initialized to
their default values:

* Static variables.
* Instance variables of class instances.
* Array elements.

The default value of a variable depends on the type of the variable and
is determined as follows:

* For a variable of a value-type, the default value is the same as
the value computed by the value-type's default constructor (11.1.1).
* For a variable of a reference-type, the default value is null.
</quote>

> http://www.geocities.com/Jeff_Louie/OOP/oop5.htm

There are a couple of slight errors in that, in the Java bit:

4) Value types *don't* actually derive from anything - only the
reference type which is used for boxing the value type derives
(indirectly) from Object. It's all a bit odd, but is spelled out in the
CLI spec.

9) Java has enums now too - they're very different to C# ones though
(and far superior, IMO).

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



Relevant Pages

  • Re: final and const java help needed for an old C++ programmer
    ... the same in java. ... be changed after initialization," and for member variables it ... immutable objects. ... The JLS sets the rules in ...
    (comp.lang.java.help)
  • Re: final and const java help needed for an old C++ programmer
    ... the same in java. ... reference final just stops the reference being changed. ... be changed after initialization," and for member variables it ...
    (comp.lang.java.help)
  • Re: java websrvice and C# code file
    ... WSDL generate public access to member variable. ... You can add accessor get/set on generated file but it's not a good idea ... > I am trying to consume a Java webservice from .Net client. ... The java classes has member variables with get and set methods. ...
    (microsoft.public.dotnet.general)
  • Re: Constructors
    ... And member variables are either reference types or primitives. ... there are times when you need explicit defensive copies in Java. ... final int[] i; ... In Java initialisation may happen later, ...
    (comp.lang.java.help)