Mike
Mike

Reputation: 41

System.InvalidCastException: Unable to cast object of type

I'm getting the following error:

Unable to cast object of type 'Holo.Virtual.Rooms.Bots.virtualBot' to type 'Holo.Virtual.Rooms.Bots.virtualRoomBot'.

Here's my code:

foreach (virtualRoomBot roomBot in _Bots.Values)  // Exception thrown here
{                    
    if (roomBot.goalX == -1)
        continue;

Holo.Virtual.Rooms.Bots.virtualBot contains:

public class virtualBot
{
    public virtualBot(int botID)
    {
        DataRow dRow;
        using (DatabaseClient dbClient = Eucalypt.dbManager.GetClient())
        {
            dRow = dbClient.getRow("SELECT * FROM roombots WHERE id = '" + botID + "'");
        }
        *There are values for the db here*
    }
}

And Holo.Virtual.Rooms.Bots.virtualRoomBot contains:

public class virtualRoomBot
{
    internal virtualRoomBot(int botID, int roomID, int roomUID,
        virtualBot Bot, virtualRoomBotStatusManager statusManager)
    {
        this.botID = botID;
        this.roomID = roomID;
        this.roomUID = roomUID;
        this.Bot = Bot;
        this.statusManager = statusManager;
    }

Upvotes: 1

Views: 8552

Answers (3)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

_Bots.Values is a collection of virtualBot and your code should be

foreach (virtualBot roomBot in _Bots.Values)
{                    
    if (roomBot.goalX == -1)
        continue;

Upvotes: 2

Minduca
Minduca

Reputation: 1181

Look at this code:

public class A { }
public class B : A { }

A a = new A();
B b = (B)a;

This code above will give "Unable to cast object of type 'A' to type 'B'." The same thing is happening to your sample of code.

if you instantiate a virtualBot, you can't just cast it to virtualRoomBot.

You should make one class inherit the other. Then, do casts in the direction that i show in the code below:

public class A { }
public class B : A { }

A a = new B();
B b = (B)a;

This should works. Hope it helps. Best regards

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66509

You should modify your foreach statement as follows:

foreach (virtualBot roomBot in _Bots.Values)

Or you could omit the explicit class type and just use the implicit type var:

foreach (var roomBot in _Bots.Values)

I also suspect that since you're specifically testing the value of roomBox.goalX, you might actually be iterating on the wrong list altogether. Did you actually mean to iterate on _Bots.Values at all? Maybe you have a _RoomBots.Values?

Upvotes: 0

Related Questions