do you have to always instantiate variables in C#?

  • Thread starter Thread starter TS
  • Start date Start date
T

TS

I am coming from vb.net. I have seen that most variables need to be
instantiated before using in c#, unlike vb.net. When you declare a variable
and immediately set it's value, does that instantiate it? Since I never call
the constructor (new xxx), I don't know that it does. Ex: int myInt = 5;

thanks
 
TS,

It depends on the type you are using. If your variable is for a
reference type (doesn't derive from System.ValueType), then by default, the
variable is null. You will have to assign something to it in order for it
to not be null.

For value types, by default, the variable is set to the value of the
structure with all the bits set to zero. For numeric types, this amounts to
a value of zero.

Hope this helps.
 
AFAIK there's no difference between VB and c#: Initialize reference types
(as they refer to nothing, that is, null initially), initialize local value
types before use (they contain garbage before use, but "int myInt = 5;"
initializes an the variable); The compiler will automatically initialize
value-type member variables to default values (=0).

Niki
 
Nicholas Paldino said:
It depends on the type you are using. If your variable is for a
reference type (doesn't derive from System.ValueType), then by default, the
variable is null. You will have to assign something to it in order for it
to not be null.

For value types, by default, the variable is set to the value of the
structure with all the bits set to zero. For numeric types, this amounts to
a value of zero.

Note that the above only applies to instance and static variables.
Local variables aren't set to anything by default, and they *must* be
definitely assigned before their first use.
 
Back
Top