473,569 Members | 2,747 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Lifetime of Static Classes and Variables

I am creating some static classes with static methods and static variables,
but I have a question: What is the lifetime of static classes and static
variables? Is there any risk that these items might be garbage collected
if they're not used for a period of time?

For example:

public static class test
{
static Collection<stri ng> coll;

public static void AddItem()
{
coll = new Collection<stri ng>();
coll.Add("abc") ;
}

public static string GetItem(int index)
{
return coll[index];
}
}

Suppose I call the AddItem method and nothing is holding a reference to this
class, what's to prevent it from being garbage collected and destroyed?

Do static members like this live for the life of the application without
being subject to garbage collection?

Thanks,

Chuck Cobb

Apr 9 '06 #1
9 20553
Is this net 2.0 version of .NET?

On my version (1.1) static can not be used to describe a class.

On my version of .NET I find static members static members live for the
duration of the application.

I can't realy imagine a circumstance where a GC could act on static
data, Ithink th GC does not go there at all and the memory is release
only on application closure.

I'd be looking to use a singleton pattern rather then have a static
collection.

-dm

Apr 10 '06 #2
Chuck Cobb <ch********@oxf ordcorp.com> wrote:
I am creating some static classes with static methods and static variables,
but I have a question: What is the lifetime of static classes and static
variables? Is there any risk that these items might be garbage collected
if they're not used for a period of time?


Static variables exist for the lifetime of the ApplicationDoma in they
live in.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 10 '06 #3
You got my curiosity going,

I sniffed around and found this excelent article by Matthew Cochran.

http://www.c-sharpcorner.com/UploadF...7-e861d5aecd87

It actuly has your exact problem in it (towards the end) and shows a
little memory problem that might occur with the way you have set up
your class (not the one you were worried about though).

Infact the other sections of the article make for good reading as well.

-dm

Apr 10 '06 #4
Static methods are not objects that are subject to garbage collection, so
they have no lifetime issues for you to deal with.

For each static field there is one copy per-appdomain - each appdomain can
have a different value. The static variable itself is not garbage
collected - it is just a memory location that contains a reference to an
object. Static fields are considered to be GC roots, so any references in
them will not be garbage collected as long as the field contains that
reference. If you change the field to point to a new reference or set the
field value to null then the object whose reference was stored there becomes
eligible for collection.

Static class constructors will run once for each appdomain they get loaded
in.

Per your example, the method AddItem() is not an object that can get
garbage collected, it is a method. Each time you call AddItem a new
Collection object will be allocated and its reference assigned to the field
coll. Any previous reference stored in that field will be eligible for
garbage collection, but the current reference will not be GCd.
"Chuck Cobb" <ch********@oxf ordcorp.com> wrote in message
news:OJ******** ******@TK2MSFTN GP05.phx.gbl...
I am creating some static classes with static methods and static variables,
but I have a question: What is the lifetime of static classes and static
variables? Is there any risk that these items might be garbage collected
if they're not used for a period of time?

For example:

public static class test
{
static Collection<stri ng> coll;

public static void AddItem()
{
coll = new Collection<stri ng>();
coll.Add("abc") ;
}

public static string GetItem(int index)
{
return coll[index];
}
}

Suppose I call the AddItem method and nothing is holding a reference to
this class, what's to prevent it from being garbage collected and
destroyed?

Do static members like this live for the life of the application without
being subject to garbage collection?

Thanks,

Chuck Cobb

Apr 10 '06 #5
th*********@gma il.com wrote:
You got my curiosity going,

I sniffed around and found this excelent article by Matthew Cochran.

http://www.c-sharpcorner.com/UploadF...7-e861d5aecd87

It actuly has your exact problem in it (towards the end) and shows a
little memory problem that might occur with the way you have set up
your class (not the one you were worried about though).

Infact the other sections of the article make for good reading as well.


It's unfortunately inaccurate in terms of methods and memory, implying
that each object carries around its own copy of all the instance
methods for that type. I'll add a comment to that effect...

Jon

Apr 10 '06 #6
Jon Skeet [C# MVP] wrote:
It's unfortunately inaccurate in terms of methods and memory, implying
that each object carries around its own copy of all the instance
methods for that type. I'll add a comment to that effect...


Grr... I would have added a comment, but their login seems to be
totally broken :(

Jon

Apr 10 '06 #7
On 10 Apr 2006 00:41:49 -0700, th*********@gma il.com wrote:
You got my curiosity going,

I sniffed around and found this excelent article by Matthew Cochran.

http://www.c-sharpcorner.com/UploadF...7-e861d5aecd87

It actuly has your exact problem in it (towards the end) and shows a
little memory problem that might occur with the way you have set up
your class (not the one you were worried about though).

Infact the other sections of the article make for good reading as well.

-dm


The author of that article has some serious misunderstandin gs when
trying to explain methods. A misunderstandin g that unfortunally seems
very common. It tries to put to much information about methods on the
heap.

Ordinary methods doesn't actually have any data at all on either the
stack or the heap. It is all stored in the code section. The only
exception is virtual/abstract methods that keep one V-Table on the
heap for each class.

So, how does method calling work? First it should be noted that static
methods and instance methods work exactly the same.

instance.Method (5);

is the same as

Method(instance ,5);

It is only when virtual methods and inheritance that it becomes a
little more complicated. When calling a virtual method, code has to
look at the instance which contains a pointer to its class. It will
then look into the V-Table to find out which method to call.

To answer the original poster. Static variables are stored once for
each class and lives until the application ends. Static classes
doesn't have anything special compared to normal classes, except for
not having a default public constructor.

--
Marcus Andrén
Apr 10 '06 #8
Thanks! This has been a good discussion and was very helpful....

Chuck Cobb

"Chuck Cobb" <ch********@oxf ordcorp.com> wrote in message
news:OJ******** ******@TK2MSFTN GP05.phx.gbl...
I am creating some static classes with static methods and static variables,
but I have a question: What is the lifetime of static classes and static
variables? Is there any risk that these items might be garbage collected
if they're not used for a period of time?

For example:

public static class test
{
static Collection<stri ng> coll;

public static void AddItem()
{
coll = new Collection<stri ng>();
coll.Add("abc") ;
}

public static string GetItem(int index)
{
return coll[index];
}
}

Suppose I call the AddItem method and nothing is holding a reference to
this class, what's to prevent it from being garbage collected and
destroyed?

Do static members like this live for the life of the application without
being subject to garbage collection?

Thanks,

Chuck Cobb

Apr 10 '06 #9
Marcus,

Thanks, I handn't picked up on the articles problem (skim reader)... I
might take a look at it again later.

Anyway I stilll don't like the idea of static collections... I personly
would use a singleton for what its worth. if nothing else it allows the
colection to be stored properly if ths class to be serialized.
-dm
-dm

Apr 11 '06 #10

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

Similar topics

1
2998
by: Torsten Mueller | last post by:
I have to create a shared library containing C++ classes with static member variables on HPUX with aCC. I can compile and link the library and a test application but when I start the program I get errors like these: /usr/lib/dld.sl: Unresolved symbol: namespaces (data) from /beda/lib/libLogicalValidation.sl /usr/lib/dld.sl: Unresolved...
2
23996
by: joes | last post by:
Hi folks! I noticed in my static example which I did in PHP that the static variable is not stored over multiple php pages. So this does differ than to other OO languages like JSP. Is this so or did I something wrong? MyClass.php: <? class MyClass
3
1243
by: Colin Desmond | last post by:
I have an MFC Extension DLL that I have flicked the /clr switch on and made a few other tweaks so it compiles and runs in a managed MFC applicaiton. The DLL contains a number of classes which contain static member variables and static methods. Are these permitted in a managed DLL? Thanks Colin
5
3594
by: mast2as | last post by:
Hi guys Here's the class I try to compile (see below). By itself when I have a test.cc file for example that creates an object which is an instance of the class SpectralProfile, it compiles fine. 1 / Now If I move the getSpectrumAtDistance( const T &dist ) method definition in SpectralProfofile.cc let's say the compiler says ...
4
2364
by: thomson | last post by:
Hi All, Can any one tell me the demerits of using static classes in Web Application,what is the scope of this kind of class Thanks in Advance Thomson
4
1488
by: JC | last post by:
Suppose an ASP.Net project contains a public static class with public methods and members that are used throughout the application. Of course being static, there is only copy of the class within the application. Now suppose two users access the Web site simultaneously. Does each user see his/her own single copy of the static class, or do...
55
6174
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
17
8360
by: Juha Nieminen | last post by:
As we know, the keyword "inline" is a bit misleading because its meaning has changed in practice. In most modern compilers it has completely lost its meaning of "a hint for the compiler to inline the function if possible" (because if the compiler has the function definition available at an instantiation point, it will estimate whether to...
4
3301
by: Rene | last post by:
Hi, I was wondering if anyone could tell me why extension methods must be declared on static classes. I mean, why not allowing them to be declared as static methods in regular instance classes? In case you are wondering, I am only curious to find out the reason for this limitation. I don't really have a need to declare extension method on...
0
7694
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7921
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7666
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5504
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2107
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 we have to send another system
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.