Csharp Data Types

An important part in the life of a C# programmer is the management of data types. Just as in C and C++, every variable has a fixed data type. Every data type provides a rich set of operators that can be used to perform a very special operation. Objects can be seen as data types as well, but we'll take a closer look at that later in this book.


C# Type Mono Signed Memory Range


Sbyte System.Sbyte Yes 1 byte –128 to 127

Short System.Int16 Yes 2 bytes –32768 to 32767

Int System.Int32 Yes 4 bytes –2147483648 to 2147483647

Long System.Int64 Yes 8 bytes –9223372036854775808 to 9223372036854775807

Byte System.Byte No 1 byte 0 to 255

Ushort System.Uint16 No 2 bytes 0 to 65535

Uint System.Uint32 No 4 bytes 0 to 4294967295

Ulong System.Uint64 No 8 bytes 0 to 18446744073709551615

Float System.Single Yes 4 bytes –1.5x10-45 to 3.4 x x1038

Double System.Double Yes 8 bytes –5.0x10-324 to 1.7x10308

Decimal System.Decimal Yes 12 bytes 1.0x10-28 to 7.9x1028

Char System.Char 2 bytes Unicode characters
Boolean System.Boolean 1 byte True or false
After this brief overview, we'll show you how variables and data types can be used efficiently. The following example shows how a variable can be declared and displayed on screen:
using System;

class Hello
{
public static void Main()
{
int x = 3;
Console.WriteLine("The value is " + x );
}
}
Declaring a variable works just like in C and C++. The way data is displayed is reminiscent of Java. We use the plus operator to connect two strings with each other. The output is not surprising:
[hs@localhost csharp]$ mono hello4.exe
The value is 3


Using the plus operator is truly easy, but it could also be a danger. In most cases, the plus operator is used as a mathematical operator. If it's used differently, the result might be a bit unexpected:
using System;

class Hello
{
public static void Main()
{
uint x = 3;
Console.WriteLine("The value is " + x + 1 );
Console.WriteLine("The value is " + (x + 1) );
}
}
We perform two operations that look pretty similar. However, the results differ significantly:
[hs@localhost csharp]$ mono hello5.exe
The value is 31
The value is 4
The first operation connects two strings. The second example performs an addition. As you can see, the plus operator has more than just one meaning.
14:21C# Tutorial