SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot
    Join Date
    Nov 2010
    Location
    ONS
    Posts
    157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Can someone tell why I am getting 0 in this?

    Code Csharp:
            static void Main(string[] args)
            {
                byte result = 255;
                byte result2=2;
                byte result1=1;
     
                try
                {
                    result2 = (byte) (result + result1);
     
                    Console.WriteLine(result2);
                    Console.Read();
                }
                catch(Exception e)
                {
                    Console.WriteLine("Error : ");
                }
            }

    I am getting output
    Code Csharp:
     
    But not the catched exception.

    When I debugged the code, I got, that in result2 = (byte) (result + result1);, result2 becomes 0 automatically.
    Why?

  2. #2
    SitePoint Mentor NightStalker-DNS's Avatar
    Join Date
    Jul 2004
    Location
    Cape Town, South Africa
    Posts
    2,873
    Mentioned
    44 Post(s)
    Tagged
    0 Thread(s)
    Is there a reason you are using byte instead of int? I have never tried adding bytes together before. Not sure if that is related to your problem though

  3. #3
    SitePoint Zealot
    Join Date
    Nov 2010
    Location
    ONS
    Posts
    157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes I wanted to know the use of Checked and Unchecked by doing this.

  4. #4
    SitePoint Author silver trophybronze trophy
    wwb_99's Avatar
    Join Date
    May 2003
    Location
    Washington, DC
    Posts
    10,623
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    I suspect it is because byte is 0-255, so you are creating an INT of 256 and casting to byte which gets you back to 0.

  5. #5
    SitePoint Zealot chieftain's Avatar
    Join Date
    Feb 2005
    Location
    Michigan
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ^^ Exactly, Byte is 0 to 255 and your computation will therefore result in an overflow. http://msdn.microsoft.com/en-us/library/5bdb6693.aspx


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •