Cannot implicitly Convert type 'Object' to 'int'. An Explicit Conversion exists (are you Missing a cast?)

Asked

Viewed 1,957 times

0

I’m trying to develop a code in my game but I’m making this mistake.

...

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 case this is where I’m wrong:

...

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

        ...
  • 1

    You’re trying to put an Object inside an int. Imagine that Object is the father of all objects, and int is the son of Object, in an analogy you are trying to put the father inside the child.

  • How could I try to fix?

  • 1

    use Convert.Toint32, it has to be an object that can be converted to int, for example a string or a decimal. What does this coupons object have of property? What type is it?

  • Already solved thank you.

  • @Vinicius actually was not solved, I gave an answer because the answers they had teach wrong.

3 answers

6

I decided to answer because the answer accepted is a mistake and the other talks about good practices, when it is just the opposite. Either it works right or it doesn’t work, there is no good practice, and only one of the solutions presented works right.

It is important to note that testing within normal use and saying that it works is not programming correctly. It is right 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 make direct conversions and consider that this is correct. Has to try to make the conversion and if it gives any problem decide what action to take. For example, it is possible to define that if an invalid text was typed, consider the number as 0 (as I did in the example below). I’m not saying this is the best fit for this code. It may be another number or it may be that the code needs to have another action, maybe warn the user of the problem and request another number, depending on the context.

It would be something like that:

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

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

To know if something works you need to test with all possibilities. You have to test things even crazy. You have to understand the whole mechanism that you’re using and test for all the paths that it can run. You have to know everything that can come back from a method, including the exceptions that it can cast. There you must treat each situation properly or change the chosen method if you have another more suitable one, as is the case above.

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

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

Documentation.

Another question with more details on the subject.

  • Could still yes, simplify only to int.TryParse(cupons, out int num6);. The int already has default value 0. Of course, depending on the version of c# that is being used, but not that it is wrong.

  • Now you can, at the time of the answer was not enough or it was too recent to answer this.

3

@Vinicius, It’s not 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 some options.

  • Int32 Convert.ToInt32(string) - Gets a string as parameter and tries to convert to Int32 (which is an alias for Int32), if unable returns an error
  • Int32 Int32.Parse(string) - Does the same of the above item
  • bool Int32.TryParse(string, out Int32) - Gets a string as a parameter and a Int32 marked with the keyword out (indicating that the variable passed 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, that 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 helped the/

  • 1

    Thanks for helping :)

1


You cannot cast to an object format and try to store in int... You have to do like this with the Convert.ToInt32()

{
   int num6 = Convert.ToInt32(Cupons);
   foreach (GamePlayer gamePlayer in WorldMgr.GetAllPlayers())
   {
      gamePlayer.AddMoney(num6);
      gamePlayer.SendMessage("({0})", Message);
  • Now giving error: Cannot Convert type 'string' to 'int'

  • you verified what your variable ta receiving by Watch? the variable is an empty string?

  • Now it will be :)

  • It worked thanks Pedro Luzio.

  • @Vinicius worked on a simple and targeted test, without considering that the user can type something wrong. Actually this is the most wrong answer. The above comment itself already indicates something wrong. It only works when the person type right. It is not the programmer who should require the user to do the right thing, it is the code that should work correctly. Note that his intuition was to do the wrong thing. If you will insist on doing wrong, at least put a message to the user warning that he can’t do anything wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.