Fundamental Programming Concepts
Total Page:16
File Type:pdf, Size:1020Kb
APPENDIX A Fundamental Programming Concepts The following information is for readers who are new to programming and need a primer on some fundamental programming concepts. If you have programmed in another language, chances are the concepts presented in this appendix are not new to you. You should, however, review the material briefly to become familiar with the C# syntax. Working with Variables and Data Types Variables in programming languages store values that can change while the program executes. For example, if you wanted to count the number of times a user tries to log in to an application, you could use a variable to track the number of attempts. A variable is a memory location where a value is stored. Using the variable, your program can read or alter the value stored in memory. Before you use a variable in your program, however, you must declare it. When you declare a variable, the compiler also needs to know what kind of data will be stored at the memory location. For example, will it be numbers or letters? If the variable will store numbers, how large can a number be? Will the variable store decimals or only whole numbers? You answer these questions by assigning a data type to the variable. A login counter, for example, only needs to hold positive whole numbers. The following code demonstrates how you declare a variable named counter in C# with an integer data type: int counter; Specifying the data type is referred to as strong typing. Strong typing results in more efficient memory management, faster execution, and compiler type checking, all of which reduces runtime errors. Runtime errors are errors that can occur while a program is running and are not caught by the compiler when you build the application. For example, incorrect rounding can occur as a result of using the wrong data types in a calculation. Once you declare the variable, you need to assign it an initial value, either in a separate statement or within the declaration statement itself. For instance, the following code: int counter = 1; is equivalent to this: int counter; counter = 1; Understanding Elementary Data Types C# supports elementary data types such as numeric, character, and date types. 325 APPENDIX A N FUNDAMENTAL PROGRAMMING CONCEPTS Integral Data Types Integral data types represent whole numbers only. Table A-1 summarizes the integral data types used in C#. Table A-1. Integral Data Types Data Type Storage Size Value Range Byte 8-bit 0 through 255 Short 16-bit –32,768 through 32,767 Integer 32-bit –2,147,483,648 through 2,147,483,647 Long 64-bit –9,223,372,036,854,775,808 through 9,223,372,036,854,775,807 Obviously, memory size is important when choosing a data type for a variable. A less obvious consideration is how easily the compiler works with the data type. The compiler performs arithmetic operations with integers more efficiently than the other types. Often, it’s better to use integers as counter variables even though a byte or short type could easily manage the maximum value reached. Non-Integral Data Types If a variable will store numbers that include decimal parts, then you must use a non-integral data type. C# supports the non-integral data types listed in Table A-2. Table A-2. Non-Integral Data Types Data Type Storage Size Value Range Single 32-bit –3.4028235E+38 through –1.401298E–45 for negative values; 1.401298E–45 through 3.4028235E+38 for positive values Double 64-bit 1.79769313486231570E+308 through –4.94065645841246544E–324 for negative values; 4.94065645841246544E–324 through 1.79769313486231570E+308 for positive values Decimal 128-bit 0 through +/–79,228,162,514,264,337,593,543,950,335 with no decimal point; 0 through +/–7.9228162514264337593543950335 with 28 places to the right of the decimal The decimal data type holds a larger number of significant digits than either the single or the double data types and it is not subject to rounding errors. Decimal data types are usually reserved for financial or scientific calculations that require a higher degree of precision. Character Data Types Character data types are for variables that hold characters used in human languages. For example, a character data type holds letters such as “a” or numbers used for display and printing such as “2 apples.” The character data types in C# are based on Unicode, which defines a character set that can represent the characters found in every language from English to Arabic and Mandarin Chinese. C# supports two character data types: char and string. The char data type holds single (16-bit) Unicode character values such as a or B. The string data type holds a sequence of Unicode characters. It can range from zero up to about two billion characters. 326 APPENDIX A N FUNDAMENTAL PROGRAMMING CONCEPTS Boolean Data Type The Boolean data type holds a 16-bit value that is interpreted as true or false. It’s used for variables that can be one of only two values, such as yes or no, or on or off. Date Data Type Dates are held as 64-bit integers where each increment represents a period of elapsed time from the start of the Gregorian calendar (1/1/0001 at 12:00 a.m.). Object Data Type An object data type is a 32-bit address that points to the memory location of another data type. It is commonly used to declare variables when the actual data type they refer to can’t be determined until runtime. Although the object data type can be a catch-all to refer to the other data types, it is the most inefficient data type when it comes to performance and should be avoided unless absolutely necessary. Nullable Types By default, value types such as the Boolean, integer, and double data types can’t be assigned a null value. This can become problematic when retrieving data from data structures such as a database that does allow nulls. When declaring a value type variable that may be assigned a null, you make it a nullable type by placing a question mark symbol (?) after the type name, like so: double salary = null; // Not allowed. double? salary = null; // allowed. Introducing Composite Data Types Combining elementary data types creates composite data types. Structures, arrays, and classes are examples of composite data types. Structures A structure data type is useful when you want to organize and work with information that does not need the overhead of class methods and constructors. It’s well suited for representing lightweight objects such as the coordinates of a point or rectangle. A single variable of type structure can store such information. You declare a structure with the struct keyword. For example, the following code creates a structure named Point to store the coordinates of a point in a two-dimensional surface: public struct Point { public int _x, _y; 327 APPENDIX A N FUNDAMENTAL PROGRAMMING CONCEPTS public Point(int x, int y) { _x = x; _y = y; } } Once you define the structure, you can declare a variable of the structure type and create a new instance of the type, like so: Point p1 = new Point(10,20); Arrays Arrays are often used to organize and work with groups of the same data type; for example, you may need to work with a group of names, so you declare an array data type by placing square brackets ([]) immediately following the variable name, like so: string[] name; The new operator is used to create the array and initialize its elements to their default values. Because the elements of the array are referenced by a zero-based index, the following array holds five elements: string[] name = new string[4]; To initialize the elements of an array when the array is declared, you use curly brackets ({}) to list the values. Since the size of the array can be inferred, you do not have to state it. string[] name = {"Bob","Bill","Jane","Judy"}; C# supports multidimensional arrays. When you declare the array, you separate the size of the dimensions by commas. The following declaration creates a two-dimensional array of integers with five rows and four columns: string[,] name = new string[4,3]; To initialize the elements of a two-dimensional array when the array is declared, you use curly brackets inside curly brackets to list the array elements. int[,] intArray = {{1,2}, {3,4}, {5,6}, {7,8}}; You access elements of the array using its name followed by the index of the element in brackets. Index numbering starts at 0 for the first element. For example, name[2] references the third element of the names array declared previously and has a value of Jane. 328 APPENDIX A N FUNDAMENTAL PROGRAMMING CONCEPTS Classes Classes are used extensively in object-oriented programming languages. Most of this book is devoted to their creation and use. At this point, it suffices to say that classes define a complex data type for an object. They contain information about how an object should behave, including its name, methods, properties, and events. The .NET Framework contains many predefined classes with which you can work. You can also create your own class type definitions. A variable defined as a class type contains an address pointer to the memory location of the object. The following code declares an object instance of the StringBuilder class defined in the .NET Framework: StringBuilder sb = new StringBuilder(); Looking at Literals, Constants, and Enumerations Although the values of variables change during program execution, literals and constants contain items of data that do not change.