Can not implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)

2

I'm trying to develop code in my game but I'm having this error.

...

case "cpsuser":
    Console.Write("Digite o apelido do usuário: ");

    string Nickname = Console.ReadLine();

    Console.Write("Digite a quantidade de Cupons");

    string Cupons = Console.ReadLine();

    Console.Write("Digite a mensagem a ser informada para o player. Por exemplo: Parabéns você recebeu 10000 Cupons.");

    string Message = Console.ReadLine();

    GamePlayer Player = WorldMgr.GetAllPlayers()
                                .FirstOrDefault(p => p.PlayerCharacter
                                                      .NickName == Nickname);

    if (Player == null)
    {
        Console.WriteLine("O usuário informado não existe ou está offline!");
    }
    else
    {
        int num6 = (object)Cupons;
        foreach (GamePlayer gamePlayer in WorldMgr.GetAllPlayers())
        {
            gamePlayer.AddMoney(num6);
            gamePlayer.SendMessage("({0})", Message);

        }
    }
    break;

...

In this case I have the error:

...

else
{
    int num6 = (object)Cupons;
    foreach (GamePlayer gamePlayer in WorldMgr.GetAllPlayers())
    {
        gamePlayer.AddMoney(num6);
        gamePlayer.SendMessage("({0})", Message);

        ...
    
asked by anonymous 18.05.2016 / 16:26

3 answers

1

You can not cast a cast to an object format and try to save it in int ... You have to do this with Convert.ToInt32()

{
   int num6 = Convert.ToInt32(Cupons);
   foreach (GamePlayer gamePlayer in WorldMgr.GetAllPlayers())
   {
      gamePlayer.AddMoney(num6);
      gamePlayer.SendMessage("({0})", Message);
    
18.05.2016 / 16:32
5

I decided to answer because the answer accepted is an error and the other speaks in good practice, when it is just the opposite. Either it works right or it does not work, there is no good practice, and only one of the solutions presented works right.

It's important to note that testing within normal usage and saying that it works is not programming correctly. The right thing is to do something that always works. So with data coming from external sources that the programmer has no control over, it is not possible to do direct conversions and consider this to be correct. You have to try to do the conversion and if there is any problem decide what action to take. For example, you can define that if invalid text was typed, consider the number as 0 (as I did in the example below). I'm not saying this is the most appropriate for this code. It may be another number, or it may be that the code needs to have another action, perhaps warning the user of the problem and requesting another number, depending on the context.

It would look something like this:

int num6;
num6 = int.TryParse(cupons, out num6) ? num6 : 0;

See running on dotNetFiddle and on CodingGround .

To know if something works you need to test with all possibilities. You have to try some really stupid things. You have to understand the whole mechanism you are using and test for all the paths it can perform. You have to know everything that can be returned from a method, including the exceptions that it can throw. There you should treat each situation appropriately or change the chosen method if you have a more appropriate one, as is the case above.

Without reading and interpreting all documentation of what you are using properly you can not do anything right and you can not say that something works. Much less can one speak of good practice. Believing in good practice is a bad practice and you will shoot yourself in the foot. Either the thing is right or wrong.

You can test both of the wrong options . First enter a word, then try again by entering a correct number and word in the second request. You will see the exception.

Documentation .

Another question with more details on the subject.

    
18.05.2016 / 19:34
2

@Vinicius, It is not a good practice to make a cast (aka unboxing ).

One of the best practices says you need to do a conversion or parse and to do this you have a few options.

  • Int32 Convert.ToInt32(string) - Receives a string as a parameter and tries convert to Int32 (which is an alias for Int32 ), if it can not return an error
  • Int32 Int32.Parse(string) - Do the same as above
  • bool Int32.TryParse(string, out Int32) - Get string as a parameter and one Int32 marked with keyword out (indicating that the passed variable will have a value at the end of the method execution). If you can convert, the variable will have the converted value and the method returns true ; Otherwise, it returns false and the variable will have the default value for Int32 , which is 0 .


In practice it would look something like this:

Int32 Convert.ToInt32(string)

int num6 = Convert.ToInt32(Cupons);

Int32 Int32.Parse(string)

int num6 = Int32.Parse(Cupons);

bool Int32.TryParse(string, out Int32)

int num6;
bool converteu = Int32.TryParse(Cupons, out num6);

I hope I have helped \ o /

    
18.05.2016 / 16:49