Burned Burned
Burned Burned

Reputation: 11

using byte/sbyte and it cant convert

so i am trying to change my code from being int into byte as my teacher want to make sure that we know how do that however i have no idea how i would do that because i am very rusty on c#. my goal is to have inumber1, inumber2 and iresult as byte but its "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)". can someone help?

 private static int DataVaildation()
    {

        //variables
        bool bUserInput;
        sbyte sbNumber;

        //below is a loop that runs at least once. the loop continues
        //iterating while the condition evaluates to true, otherwise it ends
        //and control goes to the statement immediately after it. 
        do
        {
            Console.Write("Please enter a number: ");
            //converts string into int
            bUserInput = sbyte.TryParse(Console.ReadLine(), out sbNumber);
            //this will be true if the user input could not be converted for instance a word is used
            if (!bUserInput)
            {
                Console.WriteLine("Input is not a number please input a number between -10 and +10");
                continue;
            }

            //the validation so if the inputted number from the user it will reject int and do the console.writeline.
            if (sbNumber < -11 || sbNumber < 11)
            {
                //the error message
                Console.WriteLine("Your are out of range please stay between -10 and +10");

                bUserInput = false;
            }

            //the number is in range
            else
            {
                Console.WriteLine("Vaild number!");
                //if bUserInput is true then the loop can end.
                bUserInput = true;
            }
        } while (!bUserInput); //while this evaluates to true, the loop continues.

        return sbNumber;



    }


    //option 4
    private static void AddingNegitiveAndPossitiveNumbers()
    {
        Console.WriteLine("Please give me 2 number between -10 and +10 and ill add them together\n");
        //calls apon the private static int above 
        byte iNumber1 = DataVaildation();
        int iNumber2 = DataVaildation();

        //the adding will be done here
        int iResult = iNumber1 + iNumber2;

        Console.WriteLine("The sum of {0} + {1} is {2}", iNumber1, iNumber2, iResult);
    }

Upvotes: 0

Views: 585

Answers (1)

Mehri Zareie
Mehri Zareie

Reputation: 716

Return type of static function is int. It Cannot implicitly convert type int to byte . For explicit conversion use this: byte iNumber1 = (byte)DataVaildation();

Upvotes: 1

Related Questions