JeffCarvalho JeffCarvalho - 2 months ago 16
C# Question

List contains repeated items

I was trying to do a simple task on C#, put objects into a list, I've done that before, but never encountered this problem. After a few search, encountered people with similar problems, and some solutions but none fixed my problem, here's the code.

static void GenerateRooms(int RoomsNumber)
{
int randomWidth;
int randomHeight;
Room newRoom = null;
for (int i = 0; i < RoomsNumber; i++)
{
//Create new rooms and store it on the list
randomWidth = rand.Next(_MinRoomW, _MaxRoomW + 1);
randomHeight = rand.Next(_MinRoomH, _MaxRoomH + 1);

//Room(x, y, id)
newRoom = new Room(randomWidth, randomHeight, i);

//1
_RoomsL.Insert(i, newRoom);
}
}


After comment 1, I actually search the list, and all the objects are there, from 0 to the last one, but when I exit this function to any other, like that one for instance:

static void CheckList()
{
foreach(Room nextRoom in _RoomsL)
{
Console.WriteLine(" This room have the id: " + nextRoom.GetId());
}
}


All the objects into that list have the same Id, in that case, the id is equal to the last object added on the list on the first method...

So its like that:

GenerateRooms(RoomsNumber); << at the end of this function, the list is ok.

CheckList(); << just after exiting the last function and checking the same list, all the objects are the same.


I tried using
list.Insert
too, but didn't change anything. I really don't know what to do.

Room Class.

class Room
{
//This is random.
public static Random rand = new Random();

//Room variables
public static int rWIDTH, rHEIGHT;
public static int ROOMID;

public Room(int X, int Y, int id)
{
rWIDTH = X;
rHEIGHT = Y;
ROOMID = id;
}

public int GetWidth()
{
return rWIDTH;
}

public int GetHeight()
{
return rHEIGHT;
}

public int GetId()
{
return ROOMID;
}

}

Answer
public static int ROOMID;

If it's a static variable, it persists through any instance of the class. So make it un-static.

I suggest you rework your code to look like a C# class:

First move your random variable rand to the calling class (so remove it from Room)

Then for your room class:

public class Room
{

   //Room variables
   public int Width {get;set;}
   public int Height {get;set;}
   public int RoomID {get;set;}

   public Room(int width, int height, int id)
   {
       Width = width;
       Height = height;
       RoomID = id;
   }

}

and get the properties like this:

Room room = new Room(width,height,id);
Console.WriteLine(room.Width+" is the room width");

etc.