static members

  • Thread starter Thread starter fred
  • Start date Start date
F

fred

Hi, can someone please explain to me how a static member of a class works.
For example if I have:
public Class1
public static Class2 myClass2 = new Class2;
public static Int16 thisValue = 200;
public static string thisString = "This string value";
public static boolean thisBool = True
....

if Class1 is never instantiated what value do these variables take on and
exactly when do they get these values? In other words when is Class2
instantiated?

If Class1 is instantiated and then terminated what value do these variables
have. Do the variables have their values restored immediately after the
termination of the Class1 object or does it wait for GC?

Thanks,
Fred
 
Hi

Classes can contain static member data and member
functions. When a data member is declared as static, only
one copy of the data is maintained for all objects of the
class.

Static data members are not part of objects of a given
class type; they are separate objects. As a result, the
declaration of a static data member is not considered a
definition.

HTH
Ravikanth[MVP]
 
The static members of Class1 are instantiated as soon as your program enters
a method that either references one of the static members of Class1 or
instantiates an object of type Class1. This is when Class2 is instantiated
by the static member initializer.

The Class1 member variables take on the values specified in the initializers
as shown below, and retain those values until they are changed. It doesn't
matter how many instances of Class1 you create or destroy--the static
members are stored independently of any instances of the class.
 
Bret Mulvey said:
The static members of Class1 are instantiated as soon as your program enters
a method that either references one of the static members of Class1 or
instantiates an object of type Class1. This is when Class2 is instantiated
by the static member initializer.

Note, however, that unless you have a static constructor, the runtime
may decide to set those values at any time before any of the static
members are referenced - that could (and usually is) before they would
be set normally (eg at the start of the first method which *might*
reference a member) or it could be *later* than they'd be set normally
(ie creating a new instance of the class wouldn't necessarily trigger
them being set, and nor would calling a method).

See http://www.pobox.com/~skeet/csharp/beforefieldinit.html for more
information.
 
Back
Top