Saturday, August 7, 2010

The Byte Data Type

The Byte Data Type


A byte is an unsigned number whose value can range from 0 to 255 and therefore can be stored in one byte. You can use it when you know a variable would hold a relatively small value such as people's age, the number of children of one mother, etc. To declare a variable that would hold a small natural number, use the byte keyword. Here is an example:

byte Age;

You can initialize a byte variable when declaring it or afterwards. Here is an example that uses the byte data type:

using System;

class ObjectName
{
static void Main()
{
Byte Age = 14;
Console.Write("Student Age: ");
Console.WriteLine(Age);

Age = 12;
Console.Write("Student Age: ");
Console.WriteLine(Age);
}
}

Make sure you do not use a value that is higher than 255 for a byte variable, you would receive an error. When in doubt, or when you think that there is a possibility a variable would hold a bigger value, don't use the byte data type as it doesn't like exceeding the 255 value limit.

Alternatively, you can also use the var keyword to declare the variable and initialize it with a small number. Here is an example:

using System;

class Exercise
{
static void Main()
{
var Age = 14;
Console.Write("Student Age: ");
Console.WriteLine(Age);

Age = 12;
Console.Write("Student Age: ");
Console.WriteLine(Age);
}
}

Instead of a decimal number, you can also initialize an integral variable with a hexadecimal value. When doing this, make sure the decimal equivalent is less than 255. Here is an example:

using System;

class Exercise
{
static void Main()
{
var Number = 0xFE;

Console.Write("Number: ");
Console.WriteLine(Number);
}
}

This would produce:

Number: 254
Press any key to continue . . .

No comments:

Post a Comment