user1205746
user1205746

Reputation: 3364

Will this cause a memory leak?

If I declare a static queue like this inside a public class:

public class c
{
  private string[] s={"a","b","c"};
  private static Queue<string> q = new Queue<string>(s);

  static private void SomeMethod()
  {
     private string[] s2 = {"123","345"};
     // somewhere in here I reassign the queue q = new Queue<string>(s2);
  }
}

Will my action cause a memory leak in C#? Would the garbage collection claim back the possible unused memory?

Upvotes: 0

Views: 647

Answers (4)

Henry Wilson
Henry Wilson

Reputation: 3351

It's probably worth your time to read one of the many articles on Garbage Collection and how it works e.g. http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

To answer your question though, no - that won't cause a memory leak.

Upvotes: 1

Freeman
Freeman

Reputation: 5801

If any object that 'q' referenced is no longer referenced anywhere, the garbage collector will collect it.

Upvotes: 2

Gigi
Gigi

Reputation: 29421

It shouldn't cause a memory leak. The original queue is deallocated by the garbage collector.

Upvotes: 6

Justin Niessner
Justin Niessner

Reputation: 245399

No. Nothing there will cause a leak.

Once the object that q referenced is no longer referenced anywhere, it will be garbage collected appropriately.

Upvotes: 8

Related Questions