Sams Teach Yourself C# in 24 Hours

Sams Teach Yourself C# in 24 Hours

By James Foxall and Wendy Haro-Chun

Understanding Data Types

In any programming language, it's critical that the compiler, the part of the Visual Studio framework that interprets the code you write into a language the computer can understand, fully understands the type of data you're manipulating in code. For example, if you asked the compiler to add the following values, it would get confused:

659 / "Dog"

Determining Data Type

Table 12.1. The C# Data Types

Data Type—Value Value Range
bool true or false
byte 0 to 255
char a single character
decimal –79,228,162,514,264,337,593,543,950,335 to –7.9228162514264337593543950335. Use this data type for currency values
double –1.79769313486232E308 to –4.94065645841247E-324 for negative values; 4.94065645841247E–324 to 1.79769313486232E308 for positive values
float –3.402823E38 to –1.401298E–45 for negative values; 1.401298E–45 to 3.402823E38 for positive values
int –2,147,483,648 to 2,147,483,647.
long –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
sbyte –128 to 127
short –32,768 to 32,767
uint Integers in the range from 0 to 4,294,967,295
ulong Integers in the range from 0 to 10^20
ushort Integers in the range from 0 to 65,535
Data Type—Reference Value Range
string 0 to approximately 2 billion characters
object Any type can be stored in a variable type Object

C# supports unsigned data types for short, int, and long (the types prefaces with u, such as uint). Because negative numbers are excluded (there is no sign) this has the effect of doubling the positive values for a short, an int, or a long. Signed data types are preferable and should be used unless you have a very good reason for doing otherwise (such as declaring a variable that will never hold a negative value).

Casting Data from One Data Type to Another

Informit Network