ASP.NET Programming with C# and SQL Server First Edition Chapter 2 Getting Started with ASP.NET and C# Objectives In this chapter, you will: • Create basic ASP.NET Web pages • Work with variables, constants, and data types • Use expressions and operators • Learn about operator precedence ASP.NET Programming with C# and SQL Server, First Edition 2 Introduction • The ability to store values in computer memory and manipulate those values is one of the most important aspects of programming • Variables: values stored in computer memory • Data types: categories used to classify the values, or data, stored in variables ASP.NET Programming with C# and SQL Server, First Edition 3 Creating Basic ASP.NET Web Pages • ASP.NET pages have a file extension of .aspx • ASP.NET pages can also contain HTML and XHTML elements • All .aspx documents are sent by the Web server to the scripting engine for processing – Non-ASP.NET code is ignored by the scripting engine • Web server returns the results of the ASP.NET program along with the HTML or XHTML to the client’s browser • ASP.NET code is never sent to the browser ASP.NET Programming with C# and SQL Server, First Edition 4 Creating ASP.NET Code Render Blocks • Code render blocks: define inline code or inline expressions that execute when a Web page renders • Inline code: one or more lines of code (or statements) contained within a code render block • Delimiter: a character or sequence of characters used to mark the beginning and end of a code segment – Use <% and %> to designate inline code – Scripting commands are placed within the delimiters ASP.NET Programming with C# and SQL Server, First Edition 5 Creating ASP.NET Code Render Blocks (cont’d.) • C# commands end with a semicolon (;) • ASP processing directive: provides information on how to process the code – Use <%@ and %> delimiters • @Page processing directive: uses the Language attribute to identify the language that will be used in the ASP.NET page • Inline expression: scripting code expression used within an ASP.NET page – Use <%= and %> delimiters ASP.NET Programming with C# and SQL Server, First Edition 6 Understanding Classes and Objects • Object-oriented programming (OOP): refers to the creation of reusable software objects that can be incorporated into other programs • Object: programming code and data that can be treated as an individual unit or component • Class: a template, or blueprint, from which you create new objects • Instance: an object that has been created from an existing class – When you create an object from a class, you are instantiating the object ASP.NET Programming with C# and SQL Server, First Edition 7 Understanding Classes and Objects (cont’d.) • Procedure: a logical unit containing a group of individual statements • Method: a procedure associated with a class • Property: a piece of data associated with an object • A class’s methods, properties, and other types of elements are called its members • To use an object and its method, type the object name, followed by a period, and then the method name ASP.NET Programming with C# and SQL Server, First Edition 8 Understanding Classes and Objects (cont’d.) • Argument: specific information provided to a method • Passing arguments: the process of providing an argument to a method • Text string (or literal string): text contained within double quotation marks – Empty string: a zero-length string value • To use an object’s property, type the object name, followed by a period, and then the property name • Properties are only used to store data ASP.NET Programming with C# and SQL Server, First Edition 9 Understanding Classes and Objects (cont’d.) • ASP.NET includes five built-in core objects that function at the processing tier (between the client and data storage tiers): – – – – – Request Response Session Application Server ASP.NET Programming with C# and SQL Server, First Edition 10 Displaying Program Results • Response object: represents the information that will be sent back to the client • Write() method: a method of the Response object that is used to add new text to a Web page while it is being rendered – Requires a text string as an argument – Can include HTML elements as part of the argument ASP.NET Programming with C# and SQL Server, First Edition 11 Case Sensitivity in ASP.NET • Like XHTML, C# is case sensitive • Object names are usually written with initial capitalization – Example: Response.Write() ASP.NET Programming with C# and SQL Server, First Edition 12 Adding Comments to an ASP.NET Program • Comments: nonprinting lines placed in code to contain remarks for programmers – It is good programming practice to include comments in your code • C# supports two kinds of comments: – Line comment: hides a single line of code by prefacing the line with // – Block comment: hides multiple lines of code by enclosing the block in /* and */ ASP.NET Programming with C# and SQL Server, First Edition 13 Adding Comments to an ASP.NET Program (cont’d.) • Server-side comments: – Can be used anywhere except in code render or code declaration blocks – Are not processed on the server and do not display on the rendered page – Use <%-- and --%> delimiters ASP.NET Programming with C# and SQL Server, First Edition 14 Using C# Variables and Constants • Variables: values a program stores in computer memory – Specific locations in the computer’s memory • Must first create the variable and assign it a name • “Assigning a value to a variable” means storing a value in it • A variable may contain different values at different times while the program is running ASP.NET Programming with C# and SQL Server, First Edition 15 Naming Variables • Identifier: the name assigned to a variable – Must begin with upper or lowercase ASCII letter or underscore, followed by letters, numbers, or underscores – Cannot use spaces • Cannot use keywords for identifiers • Keywords (or reserved words): special words that are part of the C# language syntax • Contextual keywords: have special meaning in C# but are not reserved as keywords • Variable names are case sensitive ASP.NET Programming with C# and SQL Server, First Edition 16 Table 2-1 C# keywords ASP.NET Programming with C# and SQL Server, First Edition 17 Naming Variables (cont’d.) Table 2-2 C# contextual keywords ASP.NET Programming with C# and SQL Server, First Edition 18 Creating Variables • Must create (declare) a variable before you can use it by specifying its data type and its name – Syntax: type variableName; • Integer data type: stores positive or negative numbers with no decimal places, or the value 0 • Can assign a value to a variable (initialize it) when declaring it – Syntax: type variableName = value; • Assignment operator (=): assigns the value on the right side of the expression to the variable on the left side ASP.NET Programming with C# and SQL Server, First Edition 19 Creating Variables (cont’d.) • The value assigned to a variable must have the same data type as the variable • Literal values (or literals): the values assigned to integer variables or other numeric variables • An error will occur if you try to use a variable that has not been assigned a value when declared or before it has been used in the program ASP.NET Programming with C# and SQL Server, First Edition 20 Displaying Variables • To print a variable, pass the variable name to the Response.Write() method – Syntax: Response.Write(variableName) – Example: int mgSodium = 2300; Response.Write(mgSodium); • Can combine text strings with variables, separated with the plus sign (+) – Example: Response.Write(“<p>Adult maximum sodium limit is” + mgSodium + “per day.</p>”); ASP.NET Programming with C# and SQL Server, First Edition 21 Modifying Variables • Can change the value of a variable at any point in a program using an assignment statement • Syntax: variableName = value; ASP.NET Programming with C# and SQL Server, First Edition 22 Creating Constants • Constant: contains information that does not change during the program execution • Constant naming rules are the same as those for variables • Use the const keyword before the data type when declaring a constant • Constants must be initialized in the declaration statement and cannot be changed later • Syntax: const type constantName = initialValue; ASP.NET Programming with C# and SQL Server, First Edition 23 Working with Data Types • Data type: the specific category of information that a variable contains • Data type is used to determine the amount of memory needed to store the variable’s value • Primitive types: data types that can be assigned only a single value • Strongly typed programming languages: languages that require the declaration of data type for variables – Also known as static typing because the data type does not change after it is declared ASP.NET Programming with C# and SQL Server, First Edition 24 Working with Data Types (cont’d.) Table 2-3 Commonly used C# primitive data types ASP.NET Programming with C# and SQL Server, First Edition 25 Working with Data Types (cont’d.) • Loosely typed programming languages: languages that do not require the declaration of data types for variables – Also known as dynamic typing, because data types can change after declaration • C# is a strongly typed programming language ASP.NET Programming with C# and SQL Server, First Edition 26 Using Numeric Data Types • Integer: a positive or negative whole number with no decimal places – Use int or long data types • Floating-point number: a number with decimal places or a number written in exponential notation – Use float, double, and decimal data types • Exponential notation (scientific notation): shortened format for writing very large numbers or numbers with many decimal places • Literal floating-point values are treated as type double by C# when used in assignment statements ASP.NET Programming with C# and SQL Server, First Edition 27 Working with Boolean Values • Boolean value: a logical value of true or false – Used for making decisions in a program – Can only use the values true and false in C# • Use the keyword bool when declaring a Boolean variable • Syntax: bool variableName = value ASP.NET Programming with C# and SQL Server, First Edition 28 Using the Char Data Type • char data type: stores any single character or escaped hexadecimal Unicode character in single quotations – Example: char semesterGrade = ‘B’; • Unicode: a standardized set of characters from many of the world’s languages • Hexadecimal: a numeral system based on the value of 16 – Uses 16 characters: 0-9 plus A through F • Hexadecimal values must be preceded by the \u escape sequence and enclosed in single quotations ASP.NET Programming with C# and SQL Server, First Edition 29 Using the String Data Type • string data type: used to store text string variables • Literal values must be enclosed in double quotations • Syntax: string variableName = “value”; • Escape character: tells the compiler or interpreter that the following character has a special purpose – In C#, the escape character is the backslash \ • Escape sequence: the escape character combined with other characters – Used to insert a special character into a string ASP.NET Programming with C# and SQL Server, First Edition 30 Table 2-4 C# escape sequences ASP.NET Programming with C# and SQL Server, First Edition 31 Casting Types • You cannot change the data type of a variable while the program is running • To use the contents of a variable as a different data type, you must cast the variable to a new data type • Casting (or type casting): copies variable’s value; converts it to store it into a variable of another type – Syntax: newVariable = (newType) oldVariable • If you do not cast a variable to another data type, C# tries to automatically cast it, provided the target value is able to store a value of the specified size ASP.NET Programming with C# and SQL Server, First Edition 32 Casting Types (cont’d.) • Can also use methods of the Convert class to manually convert variables to other data types • ToString() method: converts a variable to a string data type • Pass the name of the variable to be converted into the method of the Convert class – Syntax: Convert.ToString(variableName); ASP.NET Programming with C# and SQL Server, First Edition 33 Storing Data in Arrays • Array: set of data represented by a single variable name – Can be thought of as a collection of variables stored within a single variable – All of the data must be of the same data type ASP.NET Programming with C# and SQL Server, First Edition 34 Storing Data in Arrays (cont’d.) Figure 2-9 Conceptual example of an array ASP.NET Programming with C# and SQL Server, First Edition 35 Declaring and Initializing Arrays • Element: each piece of data stored within an array • Index: an element’s numeric position within the array – Index is enclosed in square brackets when referring to an element – Syntax: arrayName[index] • Must declare an array’s data type and number of elements – Syntax: type[] arrayName = new type[elements]; ASP.NET Programming with C# and SQL Server, First Edition 36 Declaring and Initializing Arrays (cont’d.) • To assign a value to an individual array element, include the index for the element – Syntax: arrayName[index] = value; • To access an element’s value, include the element’s index – Example: Response.Write(arrayName[index]); • To modify an element’s value, include the index for the element – Syntax: arrayName[index] = value; ASP.NET Programming with C# and SQL Server, First Edition 37 Determining the Number of Elements in an Array • Length property: returns the number of elements in an array • Syntax: arrayName.Length • Note that property names are not followed by parentheses, as method names are ASP.NET Programming with C# and SQL Server, First Edition 38 Building Expressions • Expression: a combination of literal values, variables, operators, and other expressions that can be evaluated to produce a result • Operands: variables and literals contained in an expression • Operators: symbols used in expressions to manipulate operands – Binary operator: requires an operand before and after the operator – Unary operator: requires a single operator either before or after the operator ASP.NET Programming with C# and SQL Server, First Edition 39 Table 2-5 C# operator categories ASP.NET Programming with C# and SQL Server, First Edition 40 Arithmetic Binary Operators • Arithmetic binary operators: used to perform mathematical calculations, including addition, subtraction, multiplication, division, and modulus • Modulus: divides one operand by another and returns only the remainder • The C# interpreter does not convert strings to numbers when using the addition operator – The strings are combined together ASP.NET Programming with C# and SQL Server, First Edition 41 Arithmetic Binary Operators (cont’d.) Table 2-6 Arithmetic binary operators ASP.NET Programming with C# and SQL Server, First Edition 42 Arithmetic Unary Operators • Arithmetic unary operators: allow you to perform arithmetic operations on a single variable • Prefix operator: placed before a variable – Value of the operand is returned after the operator is applied to it • Postfix operator: placed after a variable – Value of the operand is returned before the operator is applied to it ASP.NET Programming with C# and SQL Server, First Edition 43 Arithmetic Unary Operators (cont’d.) Table 2-7 Arithmetic unary operators ASP.NET Programming with C# and SQL Server, First Edition 44 Arithmetic Unary Operators (cont’d.) Figure 2-12 Program that uses the prefix increment operator ASP.NET Programming with C# and SQL Server, First Edition 45 Arithmetic Unary Operators (cont’d.) Figure 2-13 Output of the prefix version of the student ID program ASP.NET Programming with C# and SQL Server, First Edition 46 Arithmetic Unary Operators (cont’d.) Figure 2-14 Program that uses the postfix increment operator ASP.NET Programming with C# and SQL Server, First Edition 47 Arithmetic Unary Operators (cont’d.) Figure 2-15 Output of the postfix version of the student ID program ASP.NET Programming with C# and SQL Server, First Edition 48 Assignment Operators • Assignment operators: used to assign a value to a variable • Compound assignment operators: perform mathematical calculations on variables and literal values in an expression, and then assign a new value to the left operand • Concatenation operator (+): used to combine two strings ASP.NET Programming with C# and SQL Server, First Edition 49 Assignment Operators (cont’d.) Table 2-8 Assignment operators ASP.NET Programming with C# and SQL Server, First Edition 50 Comparison and Conditional Operators • Comparison operators: used to compare two operands and determine if one numeric value is greater than another – Return a Boolean value of true or false – Values being compared must be of the same data type • Nonnumeric values are compared by their hexadecimal Unicode values – Lowercase letters have higher hexadecimal values than their corresponding uppercase letters ASP.NET Programming with C# and SQL Server, First Edition 51 Comparison and Conditional Operators (cont’d.) Table 2-9 Comparison operators ASP.NET Programming with C# and SQL Server, First Edition 52 Comparison and Conditional Operators (cont’d.) • Conditional operator: returns one of two results, based on the results of a conditional expression • Syntax: conditional expression? result1: result2; • If the conditional expression evaluates to true, result1 is used; otherwise, result2 is used ASP.NET Programming with C# and SQL Server, First Edition 53 Logical Operators • Logical operators: used for comparing two Boolean operands for equality • Or (||) and And (&&): binary operators requiring two operands • Not (!): unary operator requiring a single operand ASP.NET Programming with C# and SQL Server, First Edition 54 Logical Operators (cont’d.) Table 2-10 Logical operators ASP.NET Programming with C# and SQL Server, First Edition 55 Understanding Operator Precedence • Operator precedence: refers to the order in which operations in an expression are evaluated • Operators in a higher grouping have precedence over operators in a lower grouping • Operators in the same grouping have the same order of precedence – Evaluated from left to right or right to left, depending on the operators involved • Associativity: order in which operators of equal precedence execute ASP.NET Programming with C# and SQL Server, First Edition 56 Table 2-11 C# operator categories ASP.NET Programming with C# and SQL Server, First Edition 57 Table 2-11 C# operator categories (cont’d.) ASP.NET Programming with C# and SQL Server, First Edition 58 Understanding Operator Precedence (cont’d.) Figure 2-18 Conceptual illustration of left-to-right associativity ASP.NET Programming with C# and SQL Server, First Edition 59 Understanding Operator Precedence (cont’d.) Figure 2-19 Conceptual illustration of right-to-left associativity ASP.NET Programming with C# and SQL Server, First Edition 60 Summary • Code render blocks define inline code or inline expressions that execute when a Web page renders • Use an ASP processing directive to declare the language that ASP.NET will use • Object-oriented programming (OOP): refers to the creation of reusable software objects • Comments: nonprinting lines placed in code • Variables: values stored in computer memory • Identifier is a name assigned to a variable ASP.NET Programming with C# and SQL Server, First Edition 61 Summary (cont’d.) • Keywords (reserved words): special words that are part of the C# language syntax • Constant: contains information that does not change during the program execution • Data type: category of information that a variable contains • C# is a strongly typed programming language • Integer: positive or negative number with no decimal places ASP.NET Programming with C# and SQL Server, First Edition 62 Summary (cont’d.) • Floating-point number: number with decimal places or that is written in exponential notation • Boolean value is a logical value of true or false • char data type stores any single character • string data type stores text string variables • Casting (type casting): copies the value of one variable into a variable of another data type • Array: contains a set of data represented by a single variable name ASP.NET Programming with C# and SQL Server, First Edition 63 Summary (cont’d.) • Expression: combination of literal values, variables, operators, and other expressions that can be evaluated by the C# interpreter to produce a result • Arithmetic operators: used to perform mathematical calculations • Assignment operators: assign values to variables • Comparison operators: used to compare two operands • Conditional operator: returns one of two results, based on the results of a conditional expression ASP.NET Programming with C# and SQL Server, First Edition 64 Summary (cont’d.) • Logical operators: used for comparing two Boolean operands for equality • Operator precedence: refers to the order in which operations in an expression are evaluated – Order of precedence for operators in the same precedence group is determined by the operator’s associativity ASP.NET Programming with C# and SQL Server, First Edition 65