🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

ilovepdf_merged (3).pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

IT1907.NET Framework C# Introduction C# is an object-oriented programming language that supports data encapsulation, inheritance, polymorphism, and method overriding. The C# progr...

IT1907.NET Framework C# Introduction C# is an object-oriented programming language that supports data encapsulation, inheritance, polymorphism, and method overriding. The C# programming language was developed at Microsoft in the late 1990s, headed by Anders Hejlsberg. It allows you to build various types of applications, such as web, windows, mobile, and cloud-based applications. C# has the following features: It allows you to develop both console applications and web applications. It supports garbage collection and automatic memory management. It includes native support for the Component Object Model (COM) and Windows-based applications. In C#, the values of the primitive data types are automatically initialized to zeros, and reference types like objects and classes are initialized to null. It produces a portable code. Its programs execute in a secure, controlled runtime environment. It supports generics, partial types, and anonymous methods that expand the scope, power, and range of the language. It supports language-integrated query (LINQ) and lambda expressions. LINQ enables you to write database queries in C# programming while lambda expressions are used in LINQ expressions for efficient coding..NET Framework Structure The.NET framework is a collection of tools, technologies, and languages that provides an environment to build and deploy different types of applications easily. It is a software development framework from Microsoft. The figure below describes the structure of the.NET framework and its components. Figure 1..NET framework structure (Harwani, 2015) The operating system controls tasks and manages system resources of the computer. The.NET framework runs on Microsoft Operating Systems (OS), but there are alternative versions that will work on other OS. The OS manages the hardware and software resources that support the execution of.NET applications. Common Language Runtime (CLR) is a runtime environment of the.NET framework that manages the execution of the.NET code, enables debugging and exception handling, and makes programs portable. It converts (or compiles) the source code into an intermediate language called Microsoft Intermediate Language (MSIL). The compiler called CLR Just-In-Time (JIT) compiles the MSIL code into native code (machine-language code) before it is executed. The.NET Base Class Library contains the classes and interfaces used for building applications. The classes are organized as namespaces, and the developers can use them by including these namespaces in their programs. These classes or.NET objects can be used to build and interact with ASP.NET, Windows Forms, and/or ADO.NET and XML. ADO.NET provides access to relational databases and several data sources such as SQL Server and XML. The XML is the universal format for data on the Web. It allows developers to easily describe and deliver rich, structured data from any application in a standard, consistent way. 01 Handout 1 *Property of STI  [email protected] Page 1 of 3 IT1907 ASP.NET is a unified Web development model that includes the services necessary in building enterprise-class Web applications with a minimum of coding. ASP.NET Web Forms allows the building of dynamic websites using a familiar drag- and-drop, event-driven model. ASP.NET Web Services extend the Web infrastructure to provide the means for software to connect to other software applications. The Windows Forms contain the graphical representation of any window displayed in the application. Common Language Specification (CLS) is a set of basic language features that ensures operability between the languages in the.NET environment. It is a subset of CTS. Common Type System is a formal specification that documents how types are declared, used, and managed so the CLR can use them. The CLS tells the guidelines to the compiler of each language. The.NET supports different programming languages. The VB, C++, C#, Jscript, and J# are languages supported by.NET..NET supports the following features: Interoperability –.NET includes a large library and supports several programming languages, allowing developers to write code in different languages. Language independence – The code in all the supported languages is compiled into Common Language Infrastructure (CLI) specifications, enabling the exchange of data types between programs developed in different languages. AJAX –.NET supports AJAX, which is used by developers in creating highly responsive web applications with minimal effort. Security –.NET uses assembly for code sharing, which allows only authorized categories of users or processes to call designated methods of specific classes. Common Language Runtime Development for dynamic Web pages Base Class Library ADO.NET Web services Assembly Use An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. Assemblies are the building blocks of the.NET framework applications, and they form the fundamental unit of deployment version control, reuse, activation scoping, and security permissions. Applications in.NET are deployed as an assembly. Assemblies are compiled code in.NET that contains the code that CLR executes. The entire.NET code on compilation is converted into an intermediate language code and is stored as an assembly. Assemblies can be in the form of either: EXE (executable) DLL (Dynamic-Link Library) is a module that contains functions and data that can be used by another module (application or DLL). The assembly contains metadata that provides information along with a complete description of methods, types, and other resources. The metadata includes Manifest, which stores identification information, public types, and a list of other assemblies that are used in the current assembly. Each assembly has a 128-bit version number that is presented as a set of four (4) decimal pieces: Major.Minor.Build.Revision (Ex. 8.0.1.7). This concept of versioning enables the developers to install new versions of the components that are not backward compatible. There are two (2) types of how an assembly is deployed: private and shared. Their differences are listed below: Multiple applications can use a shared assembly. Only a single application can use a private assembly. A shared assembly has to be registered in GAC. Global Assembly Cache stores assemblies specifically designated to be shared by several applications on the computer. There’s no need to register a private assembly since it is stored in the respective application’s directory. A strong name has to be created for a shared assembly while it is not required for a private assembly. A shared assembly can have multiple versions that are not backward compatibility. A private assembly with multiple versions that are not backward compatible, the application stops working. By default, all assemblies created are considered private assemblies. When a private assembly is registered in GAC with a strong name, it becomes a shared assembly. 01 Handout 1 *Property of STI  [email protected] Page 2 of 3 IT1907 Program Structure of C# A C# program consists of the following parts: Namespace declaration A class Class methods Class attributes A Main method Statements and expressions Comments The following example console application shows the structure of a C# program: Code Listing 1. Sample C# program using System; namespace ConsoleApp { class GreetingProgram { static void Main (string[] args) { Console.Write("Enter your name: "); //this prints in console string name = Console.ReadLine(); //this reads the entered input by user as string Console.Write("Enter your age: "); int age; age = Convert.ToInt32(Console.ReadLine()); //this statement converts string to int Console.WriteLine("Hi! Your name is " + name + " and your age is " + age); Console.Write("\nPress any key to exit..."); Console.ReadKey(); } } } The namespaces are used to organize classes in a project. The namespace declaration is a collection of classes. In Code Listing 1 sample program, the namespace ConsoleApp contains the class GreetingProgram. The code System is a namespace, and one (1) of its class is Console. The using keyword is used to access the classes available in a namespace. The using namespace; (e.g., using System;) declaration must appear at the beginning of a source code. Every C# program must be saved as the same with its class name with extension.cs (e.g., GreeetingProgram.cs). The statements enclosed in and // are comments and ignored by the compiler. These are used to add notes to help programmers to easily read the program. Every C# application contains one (1) Main method. The Main method is the starting point of every application, and it contains the statements that will be executed. In the sample program, the static void Main (string[] args) {} takes string array as an argument. This method must be defined in the class as a static method. The Main method contains the statements and expressions that will be executed when the program is compiled. All statements and expressions in C# end with a semicolon (;). REFERENCES: Deitel, P. and Deitel, H. (2015). Visual C# 2012 how to program (5th Ed.). USA: Pearson Education, Inc. Gaddis, T. (2016). Starting out with visual C# (4th Ed.). USA: Pearson Education, Inc Harwani, B. (2015). Learning object-oriented programming in C# 5.0. USA: Cengage Learning PTR. 01 Handout 1 *Property of STI  [email protected] Page 3 of 3 IT1907 Data Types Identifiers and Keywords An identifier is a name of a program component programmers use to uniquely identify namespaces, classes, methods,variables, constants, etc. Identifiers are user-defined words. For example, in the program shown in Code Listing 1, the identifiers are ConsoleApp, ComputeRectangleArea, length, width, area, WriteLine, and ReadKey. Code Listing 1. Sample class with identifiers using System; namespace ConsoleApp { class ComputeRectangleArea { static void Main() { int length, width, area; length = 50; width = 8; area = length * width; Console.WriteLine("The area of the rectangle is " + area); Console.ReadKey(); } } } The following are the syntax rules when naming an identifier in C#: It must start with a letter of the English alphabet or an underscore character. The identifier's name can only have any combination of letters, digits, and underscores. White spaces are not allowed. Identifiers are case sensitive. For example, the identifier Area is not the same with identifiers area or AREA. It cannot be a reserved keyword. The classes and methods in C# must always begin with a capital letter. The following are the examples of valid and invalid identifiers: Valid Identifiers Invalid Identifiers _score score_ 1score 1score is invalid because it begins with number. first_Name ScoreClass first Name first Name is invalid because it contains white space. grade1 ComputeScore class class is an invalid identifier because it is a reserved keyword. Table 1. Example valid identifiers Table 2. Example invalid identifiers Keywords are reserved words a programming language uses for its own use, and they have a special predefined meaning to the compiler. These cannot be used as identifiers. If you do use a keyword in a program, the compiler will throw an error message. Table 3 shows the list of keywords in C#. abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while Table 3. C# keywords (Harwani, 2015) 02 Handout 1 *Property of STI  [email protected] Page 1 of 5 IT1907 Variables A variable is an identifier and a memory location that stores a specific value. Variables hold a value that can be changed during program execution. For example, a variable named score is assigned an initial value of 25. When the program starts, the value of variable score will change to 25. The basic syntax of declaring a variable is as follows: data_type identifier; The data_type is one (1) of C#’s data types, and the identifier is the name of the variable. For example, int score; Variables are initialized, or assigned a value, with an equal sign followed by the value. The following are some validexamplesof declaring and initializing variables: You can initialize a variable at the time of declaration. For example: int score = 25; You can declare and initialize more than one (1) variable of the same time data type using a comma in a single statement: int score, age; score = 85; age = 24; int length = 8, width = 5; When creating a program, you must define a variable with a meaningful name that is easy to understand what value must store on it. For example, the variables gameScore and age must store integer type values. Use camelCase notation that starts with a lowercase letter for naming local variables. For example, numberOfStudents, age, totalPrice, etc. Constants A constant is an identifier and a memory location whose value cannot be changed during program execution. Constants must initialize a value at the time of declaration. The basic syntax of initializing a constant in C# is as follows: const data_type IDENTIFIER = value; Constants in C# are defined using the const keyword. For example: const double PI = 3.14159;. In the example, the constant PI with the value of 3.14159 cannot be changed during program execution. The name of the constants must be in all capital to make it easy to identify that its value must not change. Data Types Data types are used to specify a set of values and their operations associated with variables or constants. The values have a particular data type because they are stored in memory in the same format and have the same operations defined for them. A variable or constant stores data of a specific type. When declaring a variable or constant to store a data, the appropriate data type for that data must be identified. The data type will instruct the compiler what kind of value a variable or constant can hold and its operations. There are two (2) types of primitive data types in C#: Value types. These data types store the value directly. The data type int is a value type that stores its value in a memory location directly. Reference types. These data types do not store the actual value in a variable or constant. Instead, they store the reference (or address) where the value is stored. The class objects, strings, and arrays are reference types because theyholdreferences to blocks of memory and are managed on the heap. Value Types A data type is a value type if it holds the data within its own memory allocation. Value types directly store the values withinthe variable. For example, consider the following figure: In Figure 1, the variable length of int type is assigned a value of 50. When this statement is executed, the compiler will instruct the computer system to directly store 50 in the memory space allocated for the variable length. Figure 1. Memory allocation for value type 02 Handout 1 *Property of STI  [email protected] Page 2 of 5 IT1907 The table below lists the available value types in C#. Data Type Description Range of Values Default Value Example sbyte 8-bit signed integer -128 to 127 0 sbyte size = 100; short 16-bit signed integer -32,768 to 32,767 0 short score = 1400 int 32-bit signed integer -2,147,483,648 to 0 int num = 12400; 2,147,483,647 long 64-bit signed integer -263 to 263-1 0L long length = 124000L; byte 8-bit unsigned integer 0 to 255 0 byte age = 100; ushort 16-bit unsigned integer 0 to 65,535 0 ushort uScore = 1400; uint 32-bit unsigned integer 0 to 4,294,967,295 0 uint uNum = 12400; ulong 64-bit unsigned integer 0 to 264-1 0 ulong uLength = 124000L; float Single-precision 32-bit 1.5E-45 to 3.4E+38 0.0F float rate = 235.25F; floating-point number double Double-precision 64-bit 5E-324 to 1.7E+308 0.0D double price = 235.25; floating-point number bool 8-bit Logical Boolean type true or false false bool isCorrect = true; char Unicode 16-bit character '\u0000' to '\uffff' '\0' char firstLetter = 'C'; Table 4. Value types in C# (Harwani, 2015) Reference Types A reference type does not store an actual value, but it stores the address where the value is stored. It means that the reference types contain the memory locations of where the value is stored. For example, consider the figure below: Figure 2. Memory allocation for reference type In Figure 2, the compiler will instruct the computer system to select a different memory location for the variable strName.The content of the variable strName is "0x7600", which is the address or memory location of the actual string value "Jess Diaz". The reference types in C# are Strings, Objects, Arrays, and Delegates. Type Conversion Type conversion or type casting is the process of converting a value of one (1) type of data to another data type. This is used to ensure that a function correctly processes the variables. Converting a string to an integer is an example of type conversion. The following are the two (2) forms of type casting in C#: Implicit conversion. This is the conversion of a lower precision data type to a value of higher precision data type. A compiler automatically performs implicit conversion if the precision of data type to convert is lower than precision of preferred data type. For example, a variable of short data type is capable of storing values up to 32,767, and the maximum value allowed into a byte is 255; so, there will be no problem when you convert the value of byte type into a value of short data type. An example of implicit conversion includes converting the value of int data type to a value of double data type, because int data type has a lower precision than double data type. Table 5 shows the list of all the valid implicit numericconversions in C#. From To Example sbyte short, int, long, float, or double sbyte a = 25; short b = a; byte short, ushort, int, uint, long, ulong, float, or double byte a = 25; int b = a; short int, long, float, or double short a = 25; int b = a; ushort int, uint, long, ulong, float, or double ushort a = 25; long b = a; 02 Handout 1 *Property of STI  [email protected] Page 3 of 5 IT1907 From To Example int long, float, or double int a = 25; double b = a; //the value of b is 25.0 uint long, ulong, float, or double uint a = 25; long b = a; long float or double long a = 25; double b = a; ulong float or double ulong a = 25; double b = a; float double float a = 25.0F; double b = a; char ushort, int, uint, long, ulong, float, or double char a = 'a'; int b = a; //the value of b is 97 because the decimal value of character 'a' in ASCII table is 97 Table 5. Implicit numeric conversions (Deitel, P. and Deitel, H., 2015) Note: There is no implicit conversion of any data type to char type, so the values of the other integral types do not automatically convert to the char type. The bool and double data types have no possible implicit conversions to the other data types. Explicit conversion. Converting a higher precision data type to a lower precision data type is invalid, and the compiler will return an error. For example, the statements double num1 = 25.0; int num2 = a; will return an error because the precision of variable num1 of double data type is higher than the variable num2 of int type. However, explicit conversions allow the users to convert a value of higher precision data type into a value of lower precision data type by using a cast operator. The following is the general syntax of performing explicit conversion in C#: (data_type) data_to_convert; The (data_type) is the cast operator that will create a converted copy of the value in data_to_convert. For example, the following statements uses a cast operator to explicitly convert data types: //first example int num = 25; byte b = (byte) num; //second example double price = 75.5; int varA = (int) price; //the value of variable a will be 75 In the first example, the value 25 is assigned to the variable num of int type, then the converted copy of value from variable num is assigned to the variable b. The value stored in variable num is still an integer type because the cast operator created a converted copy of its value as byte data type. Explicit conversion involves the risk of losing information, i.e., from double to int data type. In the second example, the value of the variable price of double data type is copied and converted into int data type then stored in the variable varA of int data type. The cast operator dropped the decimal part of the floating-point number 75.5 to convert it to 75 as int data type. The following statements shows some of the ways on how to use the cast operator: int a = (int) 7.9; //the return value of a is 7 double b = (double) (5 + 3); //the value of b is 8.0 Console.WriteLine((int) 2.5); //the output is 2 int c = 64; char d = (char) c; //the return value of d is the character '@' The following table shows the list of all valid explicit conversions in C#. From To sbyte byte, ushort, uint, ulong, or char byte sbyte or char short sbyte, byte, ushort, uint, ulong, or char ushort sbyte, byte, short, or char int sbyte, byte, short, ushort, uint, ulong, or char uint sbyte, byte, short, ushort, int, uint, long, ulong, or char long sbyte, byte, short, ushort, int, uint, ulong, or char 02 Handout 1 *Property of STI  [email protected] Page 4 of 5 IT1907 From To ulong sbyte, byte, short, ushort, int, uint, long, or char char sybte, byte, or short float sbyte, byte, short, ushort, int, uint, long, ulong, or char double sbyte, byte, short, ushort, int, uint, long, ulong, char, or double Table 6. Explicit conversions (Deitel, P. and Deitel, H., 2015) The explicit conversion of a data type to char data type will return the corresponding character of the value from the ASCII table. int a = 64; char b = (char) a; //the value of b is the character '@' because it is the corresponding character of decimal value 64 in ASCII table REFERENCES: Deitel, P. and Deitel, H. (2015). Visual c# 2012 how to program, 5th edition. USA: Pearson Education, Inc. Gaddis, T. (2016). Starting out with visual c#, 4th edition. USA: Pearson Education, Inc. Harwani, B. (2015). Learning object-oriented programming in c# 5.0. USA: Cengage Learning PTR. 02 Handout 1 *Property of STI  [email protected] Page 5 of 5 IT1907 Operators and Expressions Operators and Expressions Operators are the symbols that represent a specific mathematical or logical processing in programming. Operatorsspecifywhich operations to perform on operands. The following are some of the operators used in C#: Arithmetic Operators Logical Operators Relational Operators Assignment Operators Arithmetic Operators – These are operators used in performing mathematical operations on numerical values. Table 1 shows the basic arithmetic operators on C#. Assume the following variable declarations: int a = 11, b = 5; Operator Description Example Return value + Adds two (2) operands a + b 16 - Subtracts the second operand from the first operand a – b 6 * Multiplies both operands a * b 55 / Divides the first operand by second operand a / b 2 % Modulus operator; returns the remainder after dividing first operand by second a % b 1 operand Table 1. C# arithmetic operators (Gaddis, 2016) Relational Operators – These are used to determine the relationship between operands of numeric values and generate a decision on that base. These return Boolean values true and false. Table 2 shows the relational operators on C#. Assume the following variable declarations: int a = 11, b = 5; Operator Description Example Return value > Determines if the value of the first operand is greater than the value of the second a > b true operand—if yes, it returns true; otherwise, false. < Determines if the value of the first operand is less than the value of the second a < b false operand—if yes, it returns true; otherwise, false. >= Determines if the value of the first operand is greater than or equal to the value of a >= b true the second operand—if yes, it returns true; otherwise, false. = 90) { Console.WriteLine("The grade of the student is A."); } else if (exam_score >= 80) { Console.WriteLine("The grade of the student is B."); } else if (exam_score >= 70) { Console.WriteLine("The grade of the student is C."); } else if (exam_score >= 60) { Console.WriteLine("The grade of the student is D."); } else { Console.WriteLine("The grade of the student is F."); } The if-else-if statement and its conditions are executed from top to bottom. When the condition in if statement is evaluated to true, the if-else-if statement will skip the other conditions and jump to the statements afterthisif-else-ifstatement. 03 Handout 1 *Property of STI  [email protected] Page 1 of 4 IT1907 Otherwise, it will continue to evaluate the conditions in else if statements. If none of the expressions is true, the statements inside the else statement is executed. An if-else-if statement can have one (1) or more else if statements and can have or no else statement at its end. For example: int exam_score = 75; if (exam_score > 95) { Console.WriteLine("The student's exam score is excellent."); } else if (exam_score < 95 && exam_score > 50) { Console.WriteLine("The student's exam score is average."); } else if (exam_score < 50) { Console.WriteLine("The student's exam is poor."); } The switch Statement The switch statement is used to execute a block of statements based on the variable to be tested for equality against predefined list of values. The general syntax of a switch statement in C# is as follows: switch (variable or expression) { case value1: //statement(s) break; case value1: //statement(s) break;... case valuen: //statement(s) break; default: //statement(s) break; } The variable or expression in the switch statement in C# can only be an integer, a floating-point number, a character, or a string type. This variable is then tested for equality to each case label from top to bottom. The value of these case labelsmust be the same data type as the variable in the switch. Each case label must contain a break statement to stop the flow control of the switch statement if the specified value of the variable matches the value in the case label. The break statementcanonly terminate the process of a switch statement or any repetition structure or looping statements in which it appears. The switch statement may or may not contain a default statement, which must appear at the end of switch statement. The default statement is used to execute statements when none of the cases match the specified variable. The defaultstatement in C# must contain a break statement. This is to make sure that the flow control will not fall through to the default statement. 03 Handout 1 *Property of STI  [email protected] Page 2 of 4 IT1907 Example switch statement with a default statement: int weekNumber = 4; switch (weekNumber) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; case 4: Console.WriteLine("Thursday"); break; case 5: Console.WriteLine("Friday"); break; case 6: Console.WriteLine("Saturday"); break; case 7: Console.WriteLine("Sunday"); break; default: Console.WriteLine("Invalid number of day."); break; } Example switch statement without default statement: char letter = 'B'; switch (letter) { case 'A': Console.WriteLine("Apple"); break; case 'B': Console.WriteLine("Banana"); break; case 'C': Console.WriteLine("Cherry"); break; case 'D': Console.WriteLine("Dewberry"); break; } 03 Handout 1 *Property of STI  [email protected] Page 3 of 4 IT1907 The Conditional Operator The conditional operator, also called as ternary operator (?:), is a special type of decision-making operator used to perform an operation that evaluates a logical expression then selects between two (2) single statements depending on whether the defined expression evaluates to true or false and evaluates it. The general syntax of ternary operator is condition ? consequence : alternative The condition must be a logical expression, and the statements in consequence and alternative must be a value oranexpression that returns a value. If the condition evaluates to true, then the statement in consequence is evaluated, and its resultbecomes the return value of the operation. If condition evaluates to false, then the statement in alternative is evaluated, and its result becomes the return value of the operation. The ternary operator does not execute a statement but returns a value, therefore can be assigned into a variable. The statements in consequence and alternative must be the same type as the variable where it will be stored. The following are examples of using ternary operator: Example 1: int sum = 4 > 2 ? 4 + 2 : 4 – 2; //the return value is 6 and assigned to the variable sum Example 2: int exam_score = 75; string result = exam_score >= 60 ? "Student passed the exam." : "Student failed the exam."; Console.WriteLine(result); The ternary operator (?:) is used as an alternative to if…else statements that contains a single statement body. REFERENCES: Deitel, P. and Deitel, H. (2015). Visual C# 2012 how to program, 5th edition. USA: Pearson Education, Inc. Gaddis, T. (2016). Starting out with visual C#, 4th edition. USA: Pearson Education, Inc. Harwani, B. (2015). Learning object-oriented programming in C# 5.0. USA: Cengage Learning PTR. 03 Handout 1 *Property of STI  [email protected] Page 4 of 4 IT1907 Looping Loops A loop refers to a construct that enables a program to execute a block of statements or a loop body repetitively as long as the defined condition evaluates to true. Looping is used when an operation needs to repeat multiple times. The C# providesthree (3) looping structures: while – This loop repeats a block of statements as long as a given condition evaluates to true. It evaluates the condition first before executing the loop body. do…while – This is similar with while loop, except that it executes the block of statements before evaluating the given condition regardless if it evaluates to true or false. for – This loop repeats a block of statement for a specified number of times. The while Loop The while loop repeats a block of statements as long as a given condition is true. The following is the general syntax of while loop in C# including an example: Syntax: For example: while (condition) { //this will print a sequence of numbers from 1 to 10 //statements in loop body int start = 1; } while (start

Use Quizgecko on...
Browser
Browser