create new object of type... seems like it a reference?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

probably something really stupid but.... I have created a 2 classes

public class PegBoard
{
public int Status;
}
public class BFSPegBoardNode
{
public PegBoard[,] BFSBoard;
public int rowFrom;
public int colFrom;
}

I have created a new object of this type
BFSPegBoardNode CurrentNode = new BFSPegBoardNode();
push it on a Queue
MyMoveQueue.Enqueue(CurrentNode);
then deQueue later on
CurrentNode = (BFSPegBoardNode)(MyMoveQueue.Dequeue());

What is happening is that the objects that exist on the queue are being
changed when i edit CurrentNode

Keep in mind... i am looking at CurrentNode... Enqueueing... Still edit
CurrentNode... then trying to push a seaparate instance.. is this not how it
works? is the queue just a queue of pointers or is my object declaration
wrong?
 
That's right - your queue contains pointers to the objects. In C# classes are
reference types, passed by reference, and structs are value types, passed by
value by defaut.
 
jmrieman said:
probably something really stupid but.... I have created a 2 classes

public class PegBoard
{
public int Status;
}
public class BFSPegBoardNode
{
public PegBoard[,] BFSBoard;
public int rowFrom;
public int colFrom;
}

I have created a new object of this type
BFSPegBoardNode CurrentNode = new BFSPegBoardNode();
push it on a Queue
MyMoveQueue.Enqueue(CurrentNode);
then deQueue later on
CurrentNode = (BFSPegBoardNode)(MyMoveQueue.Dequeue());

What is happening is that the objects that exist on the queue are being
changed when i edit CurrentNode

Keep in mind... i am looking at CurrentNode... Enqueueing... Still edit
CurrentNode... then trying to push a seaparate instance.. is this not how it
works? is the queue just a queue of pointers or is my object declaration
wrong?

The queue is a queue of references - all classes are reference types,
whereas structs are value types.

See http://www.pobox.com/~skeet/csharp/parameters.html and
http://www.pobox.com/~skeet/csharp/memory.html for a bit of discussion
around the subject. Some day I'll get round to writing an article just
on types themselves...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top