0

Byte occupies less space. If I'm not wrong, an int variable occupies 4 bytes - while a byte variable, well... as the name says, needs only 1 byte.
I thought that we used int because most of the methods out there require arguments of type int, and if we fed them byte type data they'd simply not work.
Well, I tried writing a simple method which requires int numberOne and int numberTwo, returning numberOne + numberTwo. I fed it with two type byte variables - and it worked!
I'm really new to C#, and developing in general - so sorry if there is an obvious answer I know nothing about. Sorry about my English too.
Would be anyone kind enough to explain which are the benefits of using int every time we want to work with an integer data type, even if it's just something that can be saved in within the 0-255 range?
Thanks!

static int Sum(int numberOne, int numberTwo)
{
    return numberOne + numberTwo;
}

static void Main(string[] args)
{
    byte numberOne = 1, numberTwo = 2;
    Console.WriteLine(Sum(numberOne, numberTwo));
}
  • 1
    There's an implicit conversion from `byte` to `int`, that's why the compiler doesn't complain – dcg Mar 30 '20 at 21:10
  • 4
    Does this answer your question? [Why should I use int instead of a byte or short in C#](https://stackoverflow.com/questions/1097467/why-should-i-use-int-instead-of-a-byte-or-short-in-c-sharp) – devNull Mar 30 '20 at 21:10
  • 1
    You have in front of you a machine with somewhere between a billion and a trillion bytes of storage; why are you worried about three of them? – Eric Lippert Mar 30 '20 at 21:49

1 Answers1

1

Good question!

It's important to realize that because an int is bigger than a byte, any value that fits in a byte also fits in an int without any risk of overflow or "chopping" off part of the value.

So C# defines the concept of widening conversion: converting one data type into another datatype that is "wider" in terms of allowed values.

Effectively your code is equivalent to

static int Sum(int numberOne, int numberTwo)
{
    return numberOne + numberTwo;
}

static void Main(string[] args)
{
    byte numberOne = 1, numberTwo = 2;
    int arg1 = (int)numberOne, arg2 = (int)numberTwo;
    int result = Sum(numberOne, numberTwo);
    Console.WriteLine(result);
}

Note that the result of Sum is also an int, and the Console.WriteLine(int) overload will be called.

You can see this in action if you split your last line as follows:

// Console.WriteLine(Sum(numberOne, numberTwo));
byte result = Sum(numberOne, numberTwo);
Console.WriteLine(result);

You will see that the int-to-byte "narrowing" conversion does not happen automatically because you may actually lose data here (suppose numberOne = 250 and numberTwo = 200, then 250 + 200 = 450 would fit in an int, but not in a byte without overflow).

If you want that, you should say so:

byte result = (byte)Sum(numberOne, numberTwo);

but at your own risk.

CompuChip
  • 9,143
  • 4
  • 24
  • 48