Data Types

Data Types

The major data types in C# are shown in Table 1.

Bool

true or false

Byte

unsigned 8-bit value

short

16-bit integer

int

32-bit integer

long

64-bit integer

float

32-bit floating point

double

64-bit floating point

char

16-bit character

string

16-bit characters

Table 1 - Data types in C#

 

Note that the lengths of these basic types are irrespective of the computer type or operating system. Characters and strings in C# are always 16 bits wide: to allow for representation of characters in non-Latin languages. It uses a character coding system called Unicode, in which thousands of characters for most major written languages have been defined. You can convert between variable types in the usual simple ways:

 

·  Any wider data type can have a narrower data type (having fewer bytes) assigned directly to it, and the promotion to the new type will occur automatically. If y is of type float and j is of type int, then you can write:

 

float y = 7.0f;   //y is of type float

int j;            //j is of type int

y = j;            //convert int to float

to promote an integer to a float.

 

·  You can reduce a wider type (more bytes) to a narrower type by casting it. You do this by putting the data type name in parentheses and putting it in front of the value you wish to convert:

j = (int)y; //convert float to integer

You can also write legal statements that contain casts that might fail, such as

float x = 1.0E45;

int k = (int) x;

If the cast fails, an exception error will occur when the program is executed. Boolean variables can only take on the values represented by the reserved words true and false. Boolean variables also commonly receive values as a result of comparisons and other logical operations:

int k;

boolean gtnum;

gtnum = (k > 6); //true if k is greater than 6

Unlike C or C++, you cannot assign numeric values to a Boolean variable and you cannot convert between Boolean and any other type.

 

Converting Between Numbers and Strings

To make a string from a number or a number from a string, yo u can use the Convert methods. You can usually find the right one by simply typing Convert and a dot in the development enviroment, and the system will provide you with a list of likely methods.

string s = Convert.ToString (x);

float y = Convert.ToSingle (s);

Note that “Single” means a single-precision floating point number.

Numeric objects also provide various kinds of formatting options to specify the number of decimal places:

float x = 12.341514325f;

string s =x.ToString ("###.###"); //gives 12.342

Declaring Multiple Variables

You should note that in C#, you can declare a number of variables of the same type in a single statement:

int i, j;

float x, y, z;

This is unlike VB6, where you had to specify the type of each variable as you declare it:

Dim i As Integer, j As Integer

Dim x As Single, y As Single, z As Single

Numeric Constants

Any number you type into your program is automatically of type int if it has no fractional part or type double if it does. If you want to indicate that it is a different type, you can use various suffix and prefix characters:

float loan = 1.23f; //float

long pig = 45L; //long

int color = 0x12345; //hexadecimal

 

C# also has three reserved word constants: true, false, and null, where null means an object variable that does not yet refer to any object. We’ll learn more about objects in the following chapters

Character Constants

You can represent individual characters by enclosing them in single quotes:

char c = ‘q’;

C# follows the C convention that the white space characters (non printing characters that cause the printing position to change) can be represented by preceding special characters with a backslash, as shown in Table 2. Since the backslash itself is thus a special character, it can be represented by using a double backslash

 

‘\n’

newline (line feed)

‘\r’

carriage return

‘\t’

tab character

‘\b’

Backspace

‘\f’

form feed

‘\0’

null character

‘\”

double quote

‘\’’

single quote

‘\\’

backslash

 

 

  

  

 

 

 

 

 

 

Table 2 Representations of white space and special characters.

Variables

Variable names in C# can be of any length and can be of any combination of upper- and lowercase letters and numbers, but like VB, the first character must be a letter. Note that since case is significant in C#, the following variable names all refer to different variables:

temperature

Temperature

TEMPERATURE

You must declare all C# variables that you use in a program before you use them:

int j;

float temperature;

boolean quit;

Declaring Variables as You Use Them C# also allows you to declare variables just as you need them rather than requiring that they be declared at the top of a procedure:

int k = 5;

float x = k + 3 * y;

This is very common in the object-oriented programming style, where we might declare a variable inside a loop that has no existence or scope outside that local spot in the program.

Multiple Equals Signs for Initialization

C#, like C, allows you to initialize a series of variables to the same value in a single statement

i = j = k = 0;

This can be confusing, so don’t overuse this feature. The compiler will generate the same code for:

i = 0; j = 0; k = 0;

whether the statements are on the same or successive lines.

A Simple C# Program

Now let’s look at a very simple C# program for adding two numbers together. This program is a stand-alone program, or application.

using System;

class add2

{

 

static void Main(string[] args)

{

double a, b, c;         //declare variables

a = 1.75;         //assign values

b = 3.46;

c = a + b;        //add together

//print out sum

Console.WriteLine ("sum = " + c);

}

}

This is a complete program as it stands, and if you compile it with the C# compiler and run it, it will print out the result:

sum = 5.21

Let’s see what observations we can make about this simple program: This is the way I want it.

1. You must use the using statement to define libraries of C# code that you want to use in your program. This is similar to the imports statement in VB, and similar to the C and C++ #include directive.

2. The program starts from a function called main and it must have exactly the form shown here:

static void Main(string[] args)

3. Every program module must contain one or more classes.

4. The class and each function within the class is surrounded by braces { }.

5. Every variable must be declared by type before or by the time it is used. You could just as well have written:

double a = 1.75;

double b = 3.46;

double c = a + b;

6. Every statement must terminate with a semicolon. Statements can go on for several lines but they must terminate with the semicolon.

7. Comments start with // and terminate at the end of the line.

8. Like most other languages (except Pascal), the equals sign is used to represent assignment of data.

9. You can use the + sign to combine two strings. The string “sum =” is concatenated with the string automatically converted from the double precision variable c.

10. The writeLine function, which is a member of the Console class in the System namespace, can be used to print values on the screen.

Compiling & Running This Program This simple program is called add2.cs. You can compile and execute it by in the development environment by just pressing F5.

 

Shashi Ray

Next Recommended Reading Data Type Conversion In C#