Advanced-Web-Programming.pdf
Document Details
Uploaded by FancierExtraterrestrial
University of Mumbai
2022
Tags
Full Transcript
T.Y.B.SC (I.T) SEMESTER - V (CBCS) ADVANCED WEB PROGRAMMING SUBJECT CODE: USIT503 © UNIVERSITY OF MUMBAI Dr. Suhas Pednekar Vice Chancellor University of M...
T.Y.B.SC (I.T) SEMESTER - V (CBCS) ADVANCED WEB PROGRAMMING SUBJECT CODE: USIT503 © UNIVERSITY OF MUMBAI Dr. Suhas Pednekar Vice Chancellor University of Mumbai, Mumbai Prof. Ravindra D. Kulkarni Prof. Prakash Mahanwar Pro Vice-Chancellor, Director, University of Mumbai IDOL, University of Mumbai Programme Co-ordinator : Shri Mandar Bhanushe Head, Faculty of Science and Technology IDOL Univeristy of Mumbai – 400098 Course Co-ordinator : Gouri S.Sawant Assistant Professor B.Sc.I.T, IDOL University of Mumbai- 400098 Editor : Dr Shraddha Sable S.K college of Science and Commerce Nerul. Course Writers : Mr Mohd Shahid Ansari Mohd Zakariya Assistant Professor, Maharashtra College of Arts, Science and Commerce, Mumbai Central, Mumbai Prof. : Ms Apeksha Sachin Shirke Assistant Professor, M V Mandali’s Colleges of Commerce and Science, Veera Desai Road, Andheri West. : Ms Farzin Rais Qureshi Assistant Professor, Elphinstone College M.G Road, Fort, Mumbai : Ms Sneha Datta Khajane Assistant Professor, Ghanshyamdas Saraf College, S. V. Road, Malad (w), Mumbai : Mr Dayanand Mhamane Assistant Professor, G M Vedak College of science s February 2022, Print - 1 Published by : Director, Institute of Distance and Open Learning, University of Mumbai, Vidyanagari,Mumbai - 400 098. DTP composed and Printed by: Mumbai University Press CONTENTS Chapter No. Title Page No. Unit 1. 1. Introducing.NET................................................................................................. 01 2. The C# Language................................................................................................. 20 3. Types, Objects, and Namespaces......................................................................... 47 Unit 2 4. Web Form Fundamentals...................................................................................... 84 5. Form Controls................................................................................................... 101 Unit 3 6. Error Handling, Logging and Tracing................................................................ 130 7. State Management.............................................................................................. 153 8. Styles, Themes and Master Pages...................................................................... 163 Unit 4 9. ADO.NET Fundamentals................................................................................... 173 10. Data Binding...................................................................................................... 197 11. Data Controls...................................................................................................... 212 Unit 5 12. Extensible Markup Language (XML)................................................................ 242 B. Sc. (Information Technology)T.Y.B.SC (I.T) Semester – V SEMESTER - V Course Code: USIT503 Course Name: Advanced Web Programming Periods per week (1 Period is 50 minutes) 5 Credits 2 ADVANCED WEB PROGRAMMING Hours Marks Evaluation System Theory Examination 2½ 75 Internal -- 25 Unit Details Lectures I Introducing.NET: The.NET Framework, C#, VB, and the.NET Languages, The Common Language Runtime, The.NET Class Library. The C# Language: C# Language Basics, Variables and Data Types, Variable Operations, Object-Based Manipulation, Conditional Logic, Loops, Methods. 12 Types, Objects, and Namespaces: The Basics About Classes, Building a Basic Class, Value Types and Reference Types, Understanding Namespaces and Assemblies, Advanced Class Programming. II Web Form Fundamentals: Writing Code, Using the Code-Behind Class, Adding Event Handlers, Understanding the Anatomy of an ASP.NET Application, Introducing Server Controls, Using the Page Class, Using Application Events, Configuring an ASP.NET Application. Form Controls: Stepping Up to Web Controls, Web Control Classes, List Controls, Table Controls, Web Control Events and AutoPostBack, 12 Validation, Understanding Validation, Using the Validation Controls, Rich Controls, The Calendar, The AdRotator, Pages with Multiple Views, User Controls and Graphics, User Controls, Dynamic Graphics, The Chart Control, Website Navigation: Site Maps, URL Mapping and Routing, The SiteMapPath Control, The TreeView Control, The Menu Control. III Error Handling, Logging, and Tracing: Avoiding Common Errors, Understanding Exception Handling, Handling Exceptions, Throwing Your Own Exceptions, Using Page Tracing State Management: Understanding the Problem of State, Using View State, Transferring Information Between Pages, Using Cookies, 12 Managing Session State, Configuring Session State, Using Application State, Comparing State Management Options Styles, Themes, and Master Pages: Styles, Themes, Master Page Basics, Advanced Master Pages, IV ADO.NET Fundamentals: Understanding Databases, Configuring Your Database, Understanding SQL Basics, Understanding the Data Provider Model, Using Direct Data Access, Using Disconnected Data Access. 12 Data Binding: Introducing Data Binding, Using Single-Value Data Binding, Using Repeated-Value Data Binding, Working with Data Source Controls, 10 The Data Controls: The GridView, Formatting the GridView, selecting a GridView Row, Editing with the GridView, Sorting and Paging the GridView, Using GridView Templates, The DetailsView and FormView V XML: XML Explained, The XML Classes, XML Validation, XML Display and Transforms. Security Fundamentals: Understanding Security Requirements, Authentication and Authorization, Forms Authentication, Windows 12 Authentication. ASP.NET AJAX: Understanding Ajax, Using Partial Refreshes, Using Progress Notification, Implementing Timed Refreshes, Working with the ASP.NET AJAX Control Toolkit. Books and References: Sr. No. Title Author/s Publisher Edition Year 1. Beginning ASP.NET Matthew MacDonald Apress 2012 4.5 in C# 2. C# 2015 Anne Bohem and Murach Third 2016 Joel Murach 3. Murach’s ASP.NET 4.6 Mary Delamater and SPD Sixth 2016 Web Programming in Anne Bohem C#2015 4. ASP.NET 4.0 J. Kanjilal Tata 2011 programming McGraw- Hill 5. Programming ASP.NET D.Esposito Microsoft 2011 Press (Dreamtech) 6. Beginning Visual C# K. Watson, C. Nagel, Wrox 2010 2010 J.H Padderson, J.D. (Wiley) Reid, M.Skinner 1 INTRODUCING.NET Unit Structure 1.0 Objectives 1.1 Introducing.NET 1.1.1 C#, VB, and the.NET Languages 1.1.2 Intermediate Language 1.1.3 Components of.Net Framework 1.1.4 Common Language Runtime (CLR) 1.1.5 The.NET Class Library 1.1.6 Common Type System (CTS) 1.1.7 Meta Data in.NET 1.1.8 Common Language Specification (CLS) 1.5 Example Programs 1.6 Summary 1.7 Exercise 1.8 Reference 1.0 OBJECTIVE After going through this unit you will be able to, 1. Create and Console Application with basics code. 2. Create the Application using different types of statements and loops. 3. Know about namespaces and assemblies and how to create the same. 4. Create console application using delegates and methods. 1.1 THE.NET FRAMEWORK Microsoft.NET is much more than XML Web services. At the heart of Microsoft.NET is the.NET Framework, consisting of the common language runtime and the class libraries. These two components provide the execution engine and programming APIs for building.NET applications. Applications compiled for the.NET Framework are not compiled directly to native code. Instead, they are compiled into an 1 Advanced Web intermediate language called Microsoft Intermediate Language Programming (MSIL). When an application is run for the first time, the common language runtime just-in-time compiler compiles the MSIL code into native code before it is executed. The common language runtime is more than a simple JIT compiler; it is also responsible for providing low-level execution services, such as garbage collection, exception handling, security services, and Run time type-safety checking. Because of the common language runtime's role in managing execution, programs that target the.NET Framework are sometimes called "managed" applications. The.NET Framework also includes a set of classes for building applications that run on the common language runtime. These class libraries provide rich support for a wide range of tasks, including data access, security, file IO, XML manipulation, messaging, class reflection, XML Web services, user-interface construction, text processing, ASP.NET, and Microsoft Windows services. The most unique attribute of the.NET Framework is its support for multiple languages. It provides support for over 20 programming languages including Perl, Python, and COBOL. Relying on the common language runtime, code compiled with these compilers can interoperate. The.NET Framework is composed of the four extended applications named as four blue boxes—representing 1. ASP.NET, 2. Windows Forms, 3. ADO.NET and 4. XML, and subcomponents. 22 Introducing.NET This book uses the Visual Basic language, which enables you to create readable, modern code. The.NET version of VB is similar in syntax to older flavors of VB that you may have encountered, including “classic” VB 6 and the Visual Basic for Applications (VBA) language often used to write macros in Microsoft Office programs. 1.1.1 C#, VB, and the.NET Languages This book uses the Visual Basic language, which enables you to create readable, modern code. The.NET version of VB is similar in syntax to older flavors of VB that you may have encountered, including “classic” VB 6 and the Visual Basic for Applications (VBA) language often used to write macros in Microsoft Office programs such as Word and Excel. However, you cannot convert classic VB into the.NET flavor of Visual Basic, just as you cannot convert C++ into C#. This book uses C#, Microsoft’s.NET language of preference. C# resembles Java, JavaScript, and C++ in syntax, so programmers who have coded in one of these languages will quickly feel at home. Interestingly, VB and C# are quite similar. Though the syntax is different, both VB and C# use the.NET class library and are supported by the CLR. In fact, almost any block of C# code can be translated, line by line, into an equivalent block of VB code (and vice versa). An occasional language difference pops up, but for the most part, a developer who has learned one.NET language can move quickly and efficiently to another. 3 Advanced Web There are even software tools that translate C# and VB code Programming automatically (see http://converter.telerik.com or http://tangiblesoftwaresolutions.com for examples). In short, both VB and C# are elegant, modern languages that are ideal for creating the next generation of web applications. 1.1.2 Intermediate Language All the.NET languages are compiled into another lower-level language before the code is executed. This lower level language is the Common Intermediate Language (CIL, or just IL). The CLR, the engine of.NET, uses only IL code. Because all.NET languages are based on IL, they all have profound similarities. This is the reason that the VB and C# languages provide essentially the same features and performance. In fact, the languages are so compatible that a web page written with C# can use a VB component in the same way it uses a C# component, and vice versa. The.NET Framework formalizes this compatibility with something called the Common Language Specification (CLS). Essentially, the CLS is a contract that, if respected, guarantees that a component written in one.NET language can be used in all the others. One part of the CLS is the common type system (CTS), which defines the rules for data types such as strings, numbers, and arrays that are shared in all NET languages. The CLS also defines object-oriented ingredients such as classes, methods, events, and quite a bit more. For the most part,.NET developers don’t need to think about how the CLS works, even though they rely on it every day. Following Figure shows how the.NET languages are compiled to IL. Every EXE or DLL file that you build with a.NET language contains IL code. This is the file you deploy to other computers. In the case of a web application, you deploy your compiled code to a live web server. 44 Introducing.NET Language compilation in.NET 1.1.3 Components of.NET Framework The following pointers describe the components of the.Net framework 3.5 and the job they perform: Common Language Runtime: It is built around CTS. It performs runtime tasks like memory management and garbage collection. Base Class Libraries: It is a rich set of functional base classes. 5 Advanced Web Extended Class Libraries: Programming Extended from base class libraries and designed to make it easier and faster to develop a specific application. CLS: (Common Language Specification) It defines requirements for.net languages. It contains the specifications for the.Net supported languages and implementation of language integration. CTS: (Common Type System) It provides guidelines for declaring, using and managing types at runtime and cross-language communication. Metadata and Assemblies: Metadata is the binary information describing the program, which is either stored in a portable executable file(PE) or in the memory. Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code and a set of resources like image files. Multiple programming languages: It provides unified programming model for several languages. Visual Studio.net: It is the IDE for coding with.net framework that spans the entire.net framework. Windows & COM+ services: Today’s requirements for today’s.net framework SDK is Windows and COM+ services which provides facility to access the lower level system functionality. The class framework encapsulates the following functionality: Data Access Thread management Interoperability with unmanaged code Network protocol support XML support Web services support and Windows Forms support Access to assembly meta data 66 1.1.4 Common Language Runtime Introducing.NET The CLR provides a rich level of support that simplifies application development and provides for better code reuse. The CLR provides a broad set of runtime services, including compilation, garbage collection and memory management. The CLR is built around the CTS, which defines standard, object- oriented data types that are used across all.NET programming languages. Code that runs under the control of the CLR is called managed code. Managed code allows the CLR to do the following. Read meta data that describes the component interfaces and types walk the code stack handle exceptions retrieve security information Design Goals of the CLR: 1. Simplify Development Define standards that promote code reuse provide a broad range of services, including memory management and garbage collection 2. Simplify application deployment Components use meta data instead of registration support side-by-side, multiple component versions command-line deployment (Xcopy) and uninstall(DEL) 3. support development languages provide rich base classes for developer tools and languages 4. support multiple languages define CTS that are used by all.NET languages 5. enable convergence of programming models Build languages and tools on a common framework. For example, ASP.NET, VB.NET, and C# have access to the same base classes. 7 Advanced Web Structure of the CLR: Programming 1.1.5 The.NET Class Library The.NET class library is a giant repository of classes that provide prefabricated functionality for everything from reading an XML file to sending an e-mail message. If you’ve had any exposure to Java, you may already be familiar with the idea of a class library. However, the.NET class library is more ambitious and comprehensive than just about any other programming framework. Any.NET language can use the.NET class library’s features by interacting with the right objects. This helps encourage consistency among different.NET languages and removes the need to install numerous components on your computer or web server. Some parts of the class library include features you’ll never need to use in web applications (such as the classes used to create desktop applications with Windows interfaces). Other parts of the class library are targeted directly at web development. Still more classes can be used in various programming scenarios and aren’t specific to web or Windows development. These include the base set of classes that define common variable types and the classes for data access, to name just a few. 1.1.6 Common Type System CTS defines standard, object oriented types and value types that are supported by all.NET programming languages. The CTS standards are what allow.NET to provide a unified programming model, and to support multiple languages. 88 CTS is the first prerequisite for allowing languages to interoperate. Introducing.NET This is easy to understand, if you consider that languages can only interoperate if they are based on the same system of types. In the past, type discrepancies have caused many interoperability problems, particularly for VB developers. So, CTS is an important new feature in the.NET framework. The CTS must support a range of languages, some of which are object- oriented, and some of which are not. Much has been made of the fact that COBOL is now a first class.NET language. COBOL is a procedural language, not an object-oriented one. The CTS provides two main types: Value Types Reference Types Value types are further classified into Built-in types User defined types Reference types are further classified into Pointers Objects Interfaces Value types are simple data types that roughly correspond to simple bit patterns like integers and floats. In.NET, a value type derives from the System.Object namespace, and supports an interface that provides information about the kind of data that is stored, as well as the data value. They are useful for representing simple data types, and nay not- object user defined type, including enumerations. They are known as exact types which mean that they fully describe the value they hold. Reference types are also derived from the system. Object namespace, and may hold object references. They are self typing, which means that they describe their own interface. They are very specific to the type of object you are assigning. Once the reference is assigned, you expect to query the object reference according to what its interface provides. 9 Advanced Web Some of the primitive data types are: Programming Bool Char int 8 int 16 float 32 float 64 unsigned int8 unsigned int16 Type Safety: The CTS promotes type safety, which in turn improves code stability. In.NET, type safety means that type definitions are completely known, and cannot be compromised. The CTS ensures that object references are strongly typed. It checks whether the array index out of range or not, whether the arithmetic exceptions are handled properly or not etc. 1.1.7 Metadata in.NET Meta Data is organized information that the CLR uses to provide compile time and runtime services, including: Loading of class files Memory Management Debugging Object Browsing MSIL translation no Native Code NET components are self describing, because the Meta Data is stored as part of the compiled component known in.NET as an assembly. Combine this with the fact that.NET components do not require windows registry entries, and you can immediately appreciate why deployments are so much easier in.NET. 10 10 The figure below illustrates different Meta Data Consumers: Introducing.NET reflection designers debugger profiler Proxy generator Meta Data Code Schema serialization Type Other IL Generator Browser Compilers CONTENTS OF META DATA Description of the assembly (the deployment unit) identity: name, version and culture dependencies (other assemblies) security permission that the assembly requires to run Description of the Types Base classes and interfaces Custom attributes defined by the User defined by the Compiler defined by the Framework 1.1.8 Common Language Specification(CLS) The purpose of the NET framework is to define standards that makes it easier to write robust, secure and reusable code. The NET framework extends this concept by allowing any language to participate in the framework; so long as it conforms to the specifications embodied by the common Type System and the Common Language Specification. 11 Advanced Web The common language Specification (CLS) defines conventions that Programming languages must support in order to be interoperable within.NET. The CLS defines rules that range from naming conventions for interface members, to rules governing method overloading. In order to provide interoperation, a CLS-compliant language must obey the following conventions: Public identifiers are case- sensitive. Language must be able to resolve identifiers that are equivalent to their keywords. Stricter overloading rules; a given method name may refer to any number of methods, as long as each one differs in the number of parameters, or argument types. Properties and events must follow strict naming rules. All pointers must be managed, and reference must be typed; otherwise, they cannot be verified. 1.5 EXAMPLE PROGRAMS Command Line Arguments using System; class Program { public static void Main(string[] args) { Console.WriteLine("Enter The Name ="); string name = Console.ReadLine(); Console.WriteLine("Enter The Roll No.="); int rollno = Int32.Parse (Console.ReadLine()); // Convert.ToInt32() Console.WriteLine("Enter The Percentage :"); double per = Double.Parse(Console.ReadLine()); // Convert.ToDouble() // Console.WriteLine("Name=" + name); // Console.WriteLine("Roll No.=" + rollno); // Console.WriteLine("Percentage =" + per); Console.WriteLine("name={0} \t rollno={1} \t Percentage={2}", name, rollno, per); Console.ReadKey(); // To hold the output } } 12 12 Introducing.NET Boxing and Unboxing using System; class Program { public static void Main(string[] args) { int a = 10; // Value Type object obj = a; // Refence Type Console.WriteLine("a={0} ", a); Console.WriteLine("obj={0}", obj); int b = (int) obj ; Console.WriteLine("b={0}", b); Console.ReadKey(); // To hold the output } } Conditional Operator ?: using System; class Program { public static void Main(string[] args) { Console.WriteLine("Enter The FOUR Numbers="); int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); int c = Convert.ToInt32(Console.ReadLine()); int d = Convert.ToInt32(Console.ReadLine()); int large = a > b ? a : b; int larger = large > c ? large : c; int largest = larger > d ? larger : d; Console.WriteLine("Large={0}", largest); Console.ReadKey(); // To hold the output } } 13 Advanced Web WAP to accept a number from the user and check whether it is positive, Programming negative or zero. using System; class Program { public static void Main(string[] args) { Console.WriteLine("Enter The Number"); int num = Convert.ToInt32(Console.ReadLine()); if (num > 0) { Console.WriteLine("Positive Number"); } if (num < 0) { Console.WriteLine("Negative Number"); } if (num == 0) { Console.WriteLine("Number is ZERO"); } Console.ReadKey(); // To hold the output } } WAP to accept a number from the user and check whether it is even or odd. using System; class Program { public static void Main(string[] args) { Console.WriteLine("Enter The Number"); int num = Convert.ToInt32(Console.ReadLine()); if (num % 2 == 0) 14 14 { Introducing.NET Console.WriteLine("Even Number"); } else { Console.WriteLine("Odd Number"); } Console.ReadKey(); // To hold the output } } Fall-through in Switch using System; class Program { public static void Main(string[] args) { Console.WriteLine("Enter The Option"); int opt = Convert.ToInt32(Console.ReadLine()); switch (opt) { case 1: Console.WriteLine("ONE"); goto case 3; case 2: Console.WriteLine("TWO"); break; case 3: Console.WriteLine("THREE"); break; case 4: Console.WriteLine("FOUR"); break; default : Console.WriteLine("Invalid Option"); 15 Advanced Web break; Programming } Console.ReadKey(); // To hold the output } } While Loop using System; class Program { public static void Main(string[] args) { Console.WriteLine("Incremented Loop"); int i = 1; while (i = 1) { Console.Write(j + "\t"); j--; } Console.ReadKey(); } } do while Loop int i = 1; do { Console.Write(i + "\t"); i++; } while (i 0); For Loop Console.WriteLine("Incremented Loop"); for (int i = 1; i =1;j--) { Console.Write (j+"\t"); } Foreach Loop int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for (int i = 0; i < 10; i++) { Console.Write(num[i] + "\t"); } foreach(int s in num) { Console.Write(s + "\t"); } 1.6 SUMMARY This chapter 1 gives the basic syntax of C#. It discusses about variables, keywords, data types, creation of arrays, operators, control structures, methods debugging and few example programs. After learning the above topics, you can write many useful programs and built a strong foundation for larger programming projects. 17 Advanced Web Programming 1.7 EXERCISE: REVIEW QUESTIONS Chapter 1 1) Write a note on.NET Framework. 2) Explain the data types in C#. 3) Explain the various operators in C#. 4) Discuss the various looping structures in C#. 5) Explain how arrays are created in C#. 6) What is a method? Explain its components. 7) How is debugging done in C#? Program 1) WAP to accept a character from the user and check whether it is vowel or not. 2) WAP to accept two numbers from the user and display the greater number using if...else. 3) WAP to accept three numbers from the user and display the greater number. 4) WAP to accept a year from the user and display whether it is leap year or not. 5) WAP to accept a number from the user and display the factorial. 6) WAP to accept a number from the user and display sum of digits and reverse of that number. 7) WAP to accept a number from the user and check whether it is palindrom number or not. 8) WAP to accept a number from the user and check whether it is armstrong number or not. 9) WAP to accept a number from the user and check whether it is prime number or not. 10) WAP to accept two numbers from the user and display the GCD and LCM of that numbers. 11) WAP to accept a number from the user and check whether it is perfect number or not? a. Example : 6 -> 1+2+3 = 6 28 = 1 + 2 + 4 + 7 + 14 = 28 18 18 12) WAP to display all the prime numbers between 1 to 1000? Introducing.NET 13) WAP to display all the armstrong numbers between 1 to 1000? 14) WAP to display the following output : Numbers Factorials 1 1 2 2 3 6 4 24 5 120 6 720 1.8 REFERENCE 1) The Complete Reference: C# 2) Visual C# 2012: How to program. 3) https://docs.microsoft.com/en-us/dotnet/csharp/ 19 Advanced Web Programming 2 THE C# LANGUAGE Unit Structure 2.0 The C# Language 2.1 Introduction 2.2 The.NET Languages 2.3 C# Language Basics 2.4 Variables and Data Types 2.5 Variables Operations 2.6 Keywords in C# 2.7 Object-Based Manipulation 2.7.1 The String Type 2.7.2 The Date Time and Time Span Types 2.7.3 The Array Type 2.8 Conditional Logic 2.8.1 Conditional Statements 2.9 Loops in C# 2.9.1 The for Loop 2.9.2 The foreach Loop 2.9.3 The While Loop 2.10 Methods in C# 2.10.1 Parameters 2.10.2 Method Overloading 2.11 Delegates 2.12 Summary 2.13 Questions 2.14 References 2.1 INTRODUCTION Before you can create an ASP.NET application, you need to choose a.NET language in which to program it. Both VB and C# are powerful, modern languages, and you won’t go wrong using either of them to code your web pages. Often the choice is simply a matter of personal preference or your work environment. For example, if you’ve already programmed in a 20 20 language that uses C-like syntax (for example, Java), you’ll probably The C# Language be most comfortable with C#. Or if you’ve spent a few hours writing Microsoft Excel macros in VBA, you might prefer the natural style of Visual Basic. Many developers become fluent in both. This chapter presents an overview of the C# language. You’ll learn about the data types you can use, the operations you can perform, and the code you’ll need to define functions, loops, and conditional logic. This chapter assumes that you have programmed before and are already familiar with most of these concepts—you just need to see how they’re implemented in C#. If you’ve programmed with a similar language such as Java, you might find that the most beneficial way to use this chapter is to browse through it without reading every section. This approach will give you a general overview of C#. You can then return to this chapter later as a reference when needed. But remember, though you can program an ASP.NET application without mastering all the language details, this deep knowledge is often what separates the casual programmer from the true programming guru. 2.2 THE.NET LANGUAGES The.NET Framework ships with two core languages that are commonly used for building ASP.NET applications: C# and VB. These languages are, to a large degree, functionally equivalent. Microsoft has worked hard to eliminate language conflicts in the.NET Framework. These battles slow down adoption, distract from the core framework features, and makes it difficult for the developer community to solve problems together and share solutions. According to Microsoft, choosing to program in C# instead of VB is just a lifestyle choice and won’t affect the performance, interoperability, feature set, or development time of your applications. Surprisingly, this ambitious claim is essentially true..NET also allows other third-party developers to release languages that are just as feature-rich as C# or VB. These languages (which include Eiffel, Pascal, and even COBOL) “snap in” to the.NET Framework effortlessly. In fact, if you want to install another.NET language, all you need to do is copy the compiler to your computer and add a line to register it in a configuration file. 21 Advanced Web Typically, a setup program would perform these steps for you Programming automatically. Once installed, the new compiler can transform your code creations into a sequence of Intermediate Language (IL) instructions, just as the VB and C# compilers do with VB and C# code. IL is the only language that the Common Language Runtime (CLR) recognizes. When you create the code for an ASP.NET web form, it’s changed into IL using the C# compiler (csc.exe) or the VB compiler (). Although you can perform the compilation manually, you’re more likely to let ASP.NET handle it automatically when a web page is requested. 2.3 THE C# LANGUAGE New C# programmers are sometimes intimidated by the quirky syntax of the language, which includes special characters such as semicolons (;), curly braces ({}), and backward slashes (\). Fortunately, once you get accustomed to C#, these details will quickly melt into the background. In the following sections, you’ll learn about four general principles you need to know about C# before you learn any other concepts. Case Sensitivity Some languages are case-sensitive, while others are not. Java, C, C++, and C# are all examples of case-sensitive languages. VB is not. This difference can frustrate former VB programmers who don’t realize that keywords, variables, and functions must be entered with the proper case. For example, if you try to create a conditional statement in C# by entering If instead of if, your code will not be recognized, and the compiler will flag it with an error when you try to build your application. Commenting Comments are lines of descriptive text that are ignored by the compiler. C# provides two basic types of comments. The first type is the single-line comment. In this case, the comment starts with two forward slashes and continues for the entire current line: // A single-line C# comment. Optionally, C# programmers can use comment brackets to indicate multiple-line comments: 22 22 This way, the code won’t be executed, but it will still remain in your The C# Language source code file if you need to refer to it or use it later. Statement Termination C# uses a semicolon (;) as a statement-termination character. Every statement in C# code must end with this semicolon, except when you’re defining a block structure. (Examples of such statements include methods, conditional statements, and loops, which are three types of code ingredients that you’ll learn about later in this chapter.) By omitting the semicolon, you can easily split a statement of code over multiple physical lines. You just need to remember to put the semicolon at the end of the last line to end the statement. The following code snippet demonstrates four equivalent ways to perform the same operation (adding three numbers together): // A code statement on a single line. myValue = myValue1 + myValue2 + myValue3; // A code statement split over two lines. myValue = myValue1 + myValue2 + myValue3; // A code statement split over three lines. myValue = myValue1 + myValue2 + myValue3; // Two code statements in a row. myValue = myValue1 + myValue2; myValue = myValue + myValue3; Blocks The C#, Java, and C languages all rely heavily on curly braces— parentheses with a little more attitude: {}. You can find the curly braces to the right of most keyboards (next to the P key); they share a key with the square brackets: []. Curly braces group multiple code statements together. Typically, you’ll group code statements because you want them to be repeated in a loop, executed conditionally, or grouped into a function. These are all block structures, and you’ll see all these techniques in this chapter. 23 Advanced Web But in each case, the curly braces play the same role, which makes Programming C# simpler and more concise than other languages that need a different syntax for each type of block structure. { // Code statements go here. } 2.4 VARIABLES AND DATA TYPES Variables As with all programming languages, you keep track of data in C# by using variables. Variables can store numbers, text, dates, and times, and they can even point to full-fledged objects. When you declare a variable, you give it a name and specify the type of data it will store. To declare a local variable, you start the line with the data type, followed by the name you want to use. A final semicolon ends the statement. // Declare an integer variable named errorCode. int errorCode; // Declare a string variable named myName. string myName; The variables in C#, are categorized into the following types: Value types Reference types Object types Value Type Value type variables can be assigned a value directly. They are derived from the class System.ValueType. The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value. For example if you type Console.WriteLine(sizeof(int)), you will get the output as 4, the bytes occupied by an integer. 24 24 The C# Language Reference Type The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables. In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic, and string. Object Type The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion. Data Types The types of data that a variable contain is called Datatype. A Datatype is a classification of things that share similar type of qualities or characteristics or behaviour. C# is strongly typed language so every variable and object must have a type. These are two types of data type in C#. Primitive types or predefined Eg:-byte, short, int, float, double, long, char, bool, DateTime, string object etc. Non-primitive types or user defined Eg:- class , struct, enum, interface, delegate, array. Strings and Escaped Characters C# treats text a little differently than other languages such as VB. It interprets any embedded backslash (\) as the start of a special character sequence. For example, \n means add a new line (carriage return). The most useful character literals are as follows: \" (double quote) 25 Advanced Web \n (new line) Programming \t (horizontal tab) \\ (backward slash) You can also insert a special character based on its hex code by using the syntax \x250. This inserts a single character with hex value 250 (which is a character that looks like an upside-down letter a). Note that in order to specify the backslash character (for example, in a directory name), you require two slashes. Here’s an example: // A C# variable holding the path c:\MyApp\MyFiles string path = "c:\\MyApp\\MyFiles"; Alternatively, you can turn off C# escaping by preceding a string with an @ symbol, as shown here: string path = @"c:\MyApp\MyFiles"; 2.5 VARIABLES OPERATIONS int number; number = 4 + 2 * 3;// number will be 10. number = (4 + 2) * 3; // number will be 18. You can use all the standard types of variable operations in C#. When working with numbers, you can use various math symbols, as listed in Table below C# follows the conventional order of operations, performing exponentiation first, followed by multiplication and division and then addition and subtraction. You can also control order by grouping sub expressions with parentheses: Operator Description Example + Addition 1 + 1 = 2 - Subtraction 5 - 2 = 3 * Multiplication 2 * 5 = 10 / Division 5.0 / 2 = 2.5 % Gets the remainder left after integer division 7 % 3 = 1 The operators above are designed for manipulating numbers. However, C# also allows you to use the addition operator ( + ) to join two strings: 26 26 // Join three strings together. The C# Language myName = firstName + " " + lastName; In addition, C# provides special shorthand assignment operators. Here are a few examples: // Add 10 to myValue. This is the same as myValue = myValue + 10; myValue += 10; // Multiple myValue by 3. This is the same as myValue = myValue * 3; myValue *= 3; // Divide myValue by 12. This is the same as myValue = myValue / 12; myValue /= 12; 2.6 KEYWORDS IN C# Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. There are 77 keywords. Some of them are: is, base, checked, decimal, delegate, event, explicit, extern, fixed, for each, implicit, in, internal, is, lock ,object , override, params, read only, ref, sealed, stack, alloc, unchecked, unsafe, using. Type Conversions Converting information from one data type to another is a fairly common programming task. For example, you might retrieve a user’s text input that contains the number you want to use for a calculation. Or, you might need to take a calculated value and transform it into text you can display in a web page. Conversions are of two types: widening and narrowing. Widening conversions always succeed. For example, you can always convert a 32-bit integer into a 64-bit integer. You won’t need any special code: int mySmallValue; long myLargeValue; // Get the largest possible value that can be stored as a 32-bit integer. //.NET provides a constant named Int32.MaxValue that provides this number. mySmallValue = Int32.MaxValue; // This always succeeds. No matter how large mySmallValue is, // it can be contained in myLargeValue. myLargeValue = mySmallValue; 27 Advanced Web On the other hand, narrowing conversions may or may not succeed, Programming depending on the data. If you’re converting a 32-bit integer to a 16-bit integer, you could encounter an error if the 32-bit number is larger than the maximum value that can be stored in the 16-bit data type. All narrowing conversions must be performed explicitly. C# uses an elegant method for explicit type conversion. To convert a variable, you simply need to specify the type in parentheses before the expression you’re converting. The following code shows how to change a 32-bit integer to a 16-bit integer: int count32 = 1000; short count16; // Convert the 32-bit integer to a 16-bit integer. // If count32 is too large to fit,.NET will discard some of the // information you need, and the resulting number will be incorrect. count16 = (short)count32; This process is called as Casting. 2.7 OBJECT-BASED MANIPULATION.NET is object-oriented to the core. In fact, even ordinary variables are really full-fledged objects in disguise. This means that common data types have the built-in smarts to handle basic operations (such as counting the number of characters in a string). Even better, it means you can manipulate strings, dates, and numbers in the same way in C# and in VB. You’ll learn far more about objects in Chapter 3. But even now it’s worth taking a peek at the object underpinnings in seemingly ordinary data types. For example, every type in the.NET class library includes a ToString() method. The default implementation of this method returns the class name. 28 28 In simple variables, a more useful result is returned: the string The C# Language representation of the given variable. The following code snippet demonstrates how to use the ToString() method with an integer: string myString; int myInteger = 100; // Convert a number to a string. myString will have the contents "100". myString = myInteger.ToString(); 2.7.1 The String Type One of the best examples of how class members can replace built-in functions is found with strings. In the past, every language has defined its own specialized functions for string manipulation. In.NET, however, you use the methods of the String class, which ensures consistency between all.NET languages. The following code snippet shows several ways to manipulate a string by using its object nature: string myString = "This is a test string "; myString = myString.Trim(); // = "This is a test string" myString = myString.Substring(0, 4); // = "This" myString = myString.ToUpper(); // = "THIS" myString = myString.Replace("IS", "AT"); // = "THAT" int length = myString.Length; // = 4 The first few statements use built-in methods, such as Trim(), Substring(), ToUpper(), and Replace(). These methods generate new strings, and each of these statements replaces the current myString with the new string object. The final statement uses a built-in Length property, which returns an integer that represents the number of characters in the string. Note that the Substring() method requires a starting offset and a character length. Strings use zero-based counting. This means that the first letter is in position 0, the second letter is in position 1, and so on. 29 Advanced Web You’ll find this standard of zero-based counting throughout.NET Programming Framework for the sake of consistency. Methods in System.String Class Length() Returns the number of characters in the string (as an integer). ToUpper() and ToLower() Returns a copy of the string with all the characters changed to uppercase or lowercase characters. Trim(), TrimEnd(), and TrimStart() Removes spaces (or the characters you specify) from either end (or both ends) of a string. PadLeft() and PadRight() Adds the specified character to the appropriate side of a string as many times as necessary to make the total length of the string equal to the number you specify. For example, "Hi".PadLeft(5, '@') returns the string @@@Hi. Insert() Puts another string inside a string at a specified (zero-based) index position. For example, Insert(1, "pre") adds the string pre after the first character of the current string. Remove() Removes a specified number of characters from a specified position. For example, Remove(0, 1) removes the first character. Replace() Replaces a specified substring with another string. For example, Replace("a", "b") changes all a characters in a string into b characters. Substring() Extracts a portion of a string of the specified length at the specified location (as a new string). For example, Substring(0, 2) retrieves the first two characters. StartsWith() and EndsWith() Determines whether a string starts or ends with a specified substring. For example, StartsWith("pre") will return either true or false, depending on whether the string begins with the letters pre in lowercase. 30 30 2.7.2 The DateTime and TimeSpan Types The C# Language The DateTime and TimeSpan data types also have built-in methods and properties. These class members allow you to perform three useful tasks: Extract a part of a DateTime (for example, just the year) or convert a TimeSpan to a specific representation (such as the total number of days or total number of minutes). Easily perform date calculations. Determine the current date and time and other information (such as the day of the week or whether the date occurs in a leap year) For example, the following block of code creates a DateTime object, sets it to the current date and time, and adds a number of days. It then creates a string that indicates the year that the new date falls in (for example, 2012). DateTime myDate = DateTime.Now; myDate = myDate.AddDays(100); string dateString = myDate.Year.ToString(); The next example shows how you can use a TimeSpan object to find the total number of minutes between two DateTime objects: DateTime myDate1 = DateTime.Now; DateTime myDate2 = DateTime.Now.AddHours(3000); TimeSpan difference; difference = myDate2.Subtract(myDate1); double numberOfMinutes; numberOfMinutes = difference.TotalMinutes; The DateTime and TimeSpan classes also support the + and – arithmetic operators, which do the same work as the built-in methods. That means you can rewrite the example shown earlier like this: 31 Advanced Web // Adding a TimeSpan to a DateTime creates a new DateTime. Programming DateTime myDate1 = DateTime.Now; TimeSpan interval = TimeSpan.FromHours(3000); DateTime myDate2 = myDate1 + interval; // Subtracting one DateTime object from another produces a TimeSpan. TimeSpan difference; difference = myDate2 - myDate1; Now : Gets the current date and time. Today: Gets the current date and leaves time set to 00:00:00. Year, Date, Month, Hour, Minute, Second, and Millisecond Returns one part of the DateTime object as an integer. For example, Month will return 12 for any day in December. Add() and Subtract() Adds or subtracts a TimeSpan from the DateTime. For convenience, these operations are mapped to the + and – operators, so you can use them instead when performing calculations with dates. AddYears(), AddMonths(), AddDays(), AddHours(), AddMinutes(), AddSeconds(), AddMilliseconds() Adds an integer that represents a number of years, months, and so on, and returns a new DateTime. You can use a negative integer to perform a date subtraction. IsLeapYear() Returns true or false depending on whether the specified year is a leap year. ToString() Returns a string representation of the current DateTime object. You can also use an overloaded version of this method that allows you to specify a parameter with a format string. 2.7.3 The Array Type Arrays also behave like objects in the world of.NET. (Technically, every array is an instance of the System.Array type.) For example, if you want to find out the size of a one-dimensional array, you can use the Length property or the GetLength() method, both of which return the total number of elements in an array: int[] myArray = {1, 2, 3, 4, 5}; int numberOfElements; numberOfElements = myArray.Length; // numberOfElements = 5 32 32 You can also use the GetUpperBound() method to find the highest The C# Language index number in an array. When calling GetUpperBound(), you supply a number that indicates what dimension you want to check. In the case of a one-dimensional array, you must always specify 0 to get the index number from the first dimension. In a two dimensional array, you can also use 1 for the second bound; in a three-dimensional array, you can also use 2 for the third bound; and so on. The following code snippet shows GetUpperBound() in action: int[] myArray = {1, 2, 3, 4, 5}; int bound; // Zero represents the first dimension of an array. bound = myArray. GetUpperBound(0); // bound = 4 On a one-dimensional array, GetUpperBound() always returns a number that’s one less than the length. That’s because the first index number is 0. For example, the following code snippet uses GetUpperBound() to find the total number of rows and the total number of columns in a two-dimensional array: // Create a 4x2 array (a grid with four rows and two columns). int[,] intArray = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; int rows = intArray.GetUpperBound(0) + 1; // rows = 4 int columns = intArray.GetUpperBound(1) + 1; // columns = 2 Length Returns an integer that represents the total number of elements in all dimensions of an array. For example, a 3 × 3 array has a length of 9. GetLowerBound() and GetUpperBound() Determines the dimensions of an array. As with just about everything in.NET, you start counting at zero (which represents the first dimension). Clear() Empties part or all of an array’s contents, depending on the index values that you supply. The elements revert to their initial empty values (such as 0 for numbers). IndexOf () and LastIndexOf () Searches a one-dimensional array for a specified value and returns the index number. You cannot use this with multidimensional arrays. Sort() Sorts a one-dimensional array made up of comparable data such as strings or numbers. 33 Advanced Web Reverse () Programming Reverses a one-dimensional array so that its elements are backward, from last to first. 2.8 CONDITIONAL LOGIC Conditional logic means deciding which action to take based on user input, external conditions, or other information—is the heart of programming. All conditional logic starts with a condition: a simple expression that can be evaluated to true or false. Your code can then make a decision to execute different logic depending on the outcome of the condition. To build a condition, you can use any combination of literal values or variables along with logical operators. Table below lists the basic logical operators. You can use all the comparison operators with any numeric types. With string data types, you can use only the equality operators (== and !=). C# doesn’t support other types of string comparison operators. int result; result = String.Compare("apple", "attach"); // result = -1 result = String.Compare("apple", "all"); // result = 1 result = String.Compare("apple", "apple"); // result = 0 // Another way to perform string comparisons. string word = "apple"; result = word.CompareTo("attach"); // result = -1 34 34 2.8.1 Conditional Statements The C# Language The if Statement The if statement is the if (myNumber > 10) powerhouse of conditional { logic, able to evaluate any combination of conditions // Do something. and deal with multiple and } different pieces of data. else if (myString == "hello") Here’s an example with an if { statement that features two else conditions: // Do something. An if block can have any } number of conditions. If you else test only a single condition, { you don’t need to include any else blocks. // Do something. } Keep in mind that the if construct matches one condition at most. For example, if myNumber is greater than 10, the first condition will be met. That means the code in the first conditional block will run, and no other conditions will be evaluated. Whether my String contains the text hello becomes irrelevant, because that condition will not be evaluated. If you want to check both conditions, don’t use an else block—instead, you need two if blocks back-to-back, as shown here: if (myNumber > 10) { // Do something. } if (myString == "hello") { // Do something. } The switch Statement C# also provides a switch statement that you can use to evaluate a single variable or expression for multiple possible values. The only limitation is that the variable you’re evaluating must be an integer- based data type, a bool, a char, a string, or a value from an enumeration. Other data types aren’t supported. 35 Advanced Web In the following code, each case examines the myNumber variable Programming and tests whether it’s equal to a specific integer: switch (myNumber) You’ll notice that the C# syntax inherits the convention of C/C++ { programming, which requires that case 1: every branch in a switch statement be ended by a special break keyword. // Do something. If you omit this keyword, the break; compiler will alert you and refuse to build your application. case 2: The only exception is if you choose to // Do something. stack multiple case statements directly on top of each other with no break; intervening code. default: This allows you to write one segment // Do something. of code that handles more than one case. Here’s an example: break; } switch (myNumber) Unlike the if statement, the switch statement is limited to { evaluating a single piece of case 1: information at a time. case 2: However, it provides a cleaner, clearer syntax than // This code executes if the if statement when you myNumber is 1 or 2. need to test a single variable. break; default: // Do something. break; } 2.8 LOOPS IN C# Introduction Loops allow you to repeat a segment of code multiple times. C# has three basic types of loops. You choose the type of loop based on the type of task you need to perform. Your choices are as follows: 36 36 You can loop a set number of times with a for loop. The C# Language You can loop through all the items in a collection of data by using a foreach loop. You can loop while a certain condition holds true with a while or do...while loop. The for and foreach loops are ideal for chewing through sets of data that have known, fixed sizes. The while loop is a more flexible construct that allows you to continue processing until a complex condition is met. The while loop is often used with repetitive tasks or calculations that don’t have a set number of iterations. 2.8.1 The for Loop The for loop is a basic ingredient in many programs. It allows you to repeat a block of code a set number of times, using a built-in counter. To create a for loop, you need to specify a starting value, an ending for (int i = 0; i < 10; i++) { // This code executes ten times. System.Diagnostics.Debug.Write(i); } value, and the amount to increment with each pass. Here’s one example: You’ll notice that the for loop starts with parentheses that indicate three important pieces of information. The first portion (int i = 0) creates the counter variable (i) and sets its initial value (0). The third portion (i++) increments the counter variable. In this example, the counter is incremented by 1 after each pass. That means i will be equal to 0 for the first pass, equal to 1 for the second pass, and so on. However, you could adjust this statement so that it decrements the counter (or performs any other operation you want). string[] stringArray = {"one", "two", "three"}; for (int i = 0; i < stringArray.Length; i++) { System.Diagnostics.Debug.Write(stringArray[i] + " "); } 37 Advanced Web The middle portion (i < 10) specifies the condition that must be met Programming for the loop to continue. This condition is tested at the start of every pass through the block. If i is greater than or equal to 10, the condition will evaluate to false, and the loop will end. 2.8.2 The foreach Loop C# also provides a foreach loop that allows you to loop through the items in a set of data. With a foreach loop, you don’t need to create an explicit counter variable. Instead, you create a variable that represents the type of data for which you’re looking. Your code will then loop until you’ve had a chance to process each piece of data in the set. The foreach loop is particularly useful for traversing the data in collections and arrays. For example, the next code segment loops through the items in an array by using foreach. string[] stringArray = {"one", "two", "three"}; foreach (string element in stringArray) { // This code loops three times, with the element variable set to // "one", then "two", and then "three". System.Diagnostics.Debug.Write(element + " "); } This code has exactly the same effect as the example in the previous section, but it’s a little simpler: In this case, the foreach loop examines each item in the array and tries to convert it to a string. Thus, the foreach loop defines a string variable named element. If you used a different data type, you’d receive an error. The foreach loop has one key limitation: it’s read-only. For example, if you wanted to loop through an array and change the values in that array at the same time, foreach code wouldn’t work. 38 38 The C# Language int[] intArray = {1,2,3}; foreach (int num in intArray) { num += 1; } Here’s an example of some flawed code: 2.8.3 The While Loop Finally, C# supports a while loop that tests a specific condition before or after each pass through the loop. When this condition evaluates to false, the loop is exited. Here’s an example that loops ten times. At the beginning of each pass, the code evaluates whether the counter (i) is less than some upper limit (in this case, 10). If it is, the loop performs iteration. int i = 0; while (i < 10) { i += 1; // This code executes ten times. } You can also place the condition at the end of the loop by using the do...while syntax. In this case, the condition is tested at the end of each pass through the loop: int i = 0; do { i += 1; // This code executes ten times. } while (i < 10); 39 Advanced Web Programming 2.9 METHODS IN C# Methods are the most basic building block you can use to organize your code. Essentially, a method is a named grouping of one or more lines of code. Ideally, each method will perform a distinct, logical task. By breaking down your code into methods, you not only simplify your life, but also make it easier to organize your code into classes and step into the world of object-oriented programming. When you declare a method in C#, the first part of the declaration specifies the data type of the return value, and the second part indicates the method name. If your method doesn’t return any information, you should use the void keyword instead of a data type at the beginning of the declaration. // This method doesn’t return any information. void MyMethodNoReturnedData() { // Code goes here. } // This method returns an integer. int MyMethodReturnsData() { // As an example, return the number 10. return 10; } Notice that the method name is always followed by parentheses. This allows the compiler to recognize that it’s a method. In this example, the methods don’t specify their accessibility. This is just a common C# convention. You’re free to add an accessibility keyword (such as public or private), as shown here: 40 40 The C# Language private void MyMethodNoReturnedData() { // Code goes here. } The accessibility determines how different classes in your code can interact. Private methods are hidden from view and are available only locally, whereas public methods can be called by all the other classes in your application. To really understand what this means, you’ll need to read the next chapter, which discusses accessibility in more detail. Invoking your methods is straightforward—you simply type the name of the method, followed by parentheses. If your method returns data, you have the option of using the data it returns or just ignoring it: // This call is allowed. MyMethodNoReturnedData(); // This call is allowed. MyMethodReturnsData(); // This call is allowed. int myNumber; myNumber = MyMethodReturnsData(); // This call isn’t allowed. // MyMethodNoReturnedData() does not return any information. myNumber = MyMethodNoReturnedData(); 2.9.1 Parameters Methods can also accept information through parameters. Parameters are declared in a similar way to variables. By convention, parameter names always begin with a lowercase letter in any language. 41 Advanced Web Here’s how you might create a function that accepts two parameters Programming and returns their sum: private int AddNumbers(int number1, int number2) { return number1 + number2; } When calling a method, you specify any required parameters in parentheses or use an empty set of parentheses if no parameters are required: // Call a method with no parameters. MyMethodNoReturnedData(); // Call a method that requires two integer parameters. MyMethodNoReturnedData2(10, 20); // Call a method with two integer parameters and an integer return value. int returnValue = AddNumbers(10, 10); 2.9.2 Method Overloading C# supports method overloading, which allows you to create more than one method with the same name but with a different set of parameters. When you call the method, the CLR automatically chooses the correct version by examining the parameters you supply. This technique allows you to collect different versions of several methods together. For example, you might allow a database search that returns an array of Product objects representing records in the database. Rather than create three methods with different names depending on the criteria, such as GetAllProducts(), GetProductsInCategory(), and GetActiveProducts(), you could create three versions of the GetProducts() method. Each method would have the same name but a different signature, meaning it would require different parameters. This example provides two overloaded versions for the GetProductPrice() method: 42 42 The C# Language private decimal GetProductPrice(int ID) { // Code here. } private decimal GetProductPrice(string name) { // Code here. } // And so on... Now you can look up product prices based on the unique product ID or the full product name, depending on whether you supply an integer or string argument: decimal price; // Get price by product ID (the first version). price = GetProductPrice(1001); // Get price by product name (the second version). price = GetProductPrice("DVD Player"); You cannot overload a method with versions that have the same signature that is, the same number of parameters and parameter data types because the CLR will not be able to distinguish them from each other. When you call an overloaded method, the version that matches the parameter list you supply is used. If no version matches, an error occurs. Optional and Named Parameters Method overloading is a time-honored technique for making methods more flexible, so you can call them in a variety of ways. C# also has another feature that supports the same goal: optional parameters. An optional parameter is any parameter that has a default value. If your method has normal parameters and optional parameters, the optional parameters must be placed at the end of the parameter list. Here’s an example of a method that has a single optional parameter: 43 Advanced Web Programming 2.11 DELEGATES Delegates allow you to create a variable that “points” to a method. You can then use this variable at any time to invoke the method. Delegates help you write flexible code that can be reused in many situations. They’re also the basis for events, an important.NET concept that you’ll consider in the next chapter. The first step when using a delegate is to define its signature. The signature is a combination of several pieces of information about a method: its return type, the number of parameters it has, and the data type of each parameter. private string GetUserName(int ID, bool useShortForm = false) { // Code here. } // Explicitly set the useShortForm parameter. name = GetUserName(401, true); // Don't set the useShortForm parameter, and use the default value (false). name = GetUserName(401); A delegate variable can point only to a method that matches its specific signature. In other words, the method must have the same return type, the same number of parameters, and the same data type for each parameter as the delegate. For example, if you have a method that accepts a single string parameter and another method that accepts two string parameters, you’ll need to use a separate delegate type for each method. To consider how this works in practice, assume that your program has the following method: private string TranslateEnglishToFrench(string english) { // Code goes here. } 44 44 This method accepts a single string argument and returns a string. The C# Language With those two details in mind, you can define a delegate that matches this signature. Here’s how you would do it: Notice that the name you choose for the parameters and the name of the delegate don’t matter. private delegate string StringFunction(string inputString); The only requirement is that the data types for the return value and parameters match exactly. Once you’ve defined a type of delegate, you can create and assign a delegate variable at any time. Using the String Function delegate type, you could create a delegate variable like this: Using your delegate variable, you can point to any method that has the matching signature. In this example, the StringFunction delegate type requires one string parameter and returns a string. Thus, you can use the functionReference variable to store a reference to the TranslateEnglishToFrench() method string frenchString; frenchString = functionReference("Hello"); Now that you have a delegate variable that references a method, you can invoke the method through the delegate. To do this, you just use the delegate name as though it were the method name: In the previous code example, the method that the function Reference delegate points to will be invoked with the parameter value "Hello", and the return value will be stored in the French String variable. StringFunction functionReference; functionReference = TranslateEnglishToFrench; The following code shows all these steps—creating a delegate variable, assigning a method, and calling the method—from start to finish: 2.12 SUMMARY: This chapter 2 gives the basic syntax of OOP in C#. It discusses about class, methods, constructors, destructor, method overloading and few example programs. After learning the above topics, you can write many useful programs and built a strong foundation for larger programming projects. 45 Advanced Web Programming 2.13 QUESTIONS 1) Explain OOP in C#. 2) Explain class and its member in C#. 3) Explain the methods in C#. 4) Explain constructor with example in C#. 5) Explain method overloading with example in C#. 6) Explain properties and indexer in C#? 7) Explain inheritance with example. 8) Explain method overriding with example. 9) Explain abstract class. 10) Explain Interface with example. 11) Explain structure with example. 2.14 REFERENCES: 1) The Complete Reference: C# 2) Visual C# 2012: How to program. 3) https://docs.microsoft.com/en-us/dotnet/csharp/ 46 46 3 TYPES, OBJECTS, AND NAMESPACES Unit Structure 3.0 Types, Objects, and Namespaces 3.1 Introduction 3.2 The Basics about Classes 3.2.1 Objects in C# 3.2.2 Constructors 3.2.3 Destructors 3.3 Building a Basic Class 3.3.1 Static Data Members and Member Functions 3.3.2 this Object in C# 3.3.3 Access Specifier 3.3.4 Adding Properties in Class 3.4 Value Types and Reference Types 3.5 Understanding Namespaces and Assemblies 3.5.1 using Keyword 3.5.2 Nested Namespace 3.5.3 Assemblies in C# 3.6 Advanced Class Programming 3.6.1 Inheritance in C# 3.6.2 Interfaces in C# 3.6.3 Delegates in C# 3.7 Summary 3.8 Questions 3.9 References 3.1 INTRODUCTION In this chapter, you’ll learn how objects are defined and how you manipulate them in your code. Taken together, these concepts are the basics of what’s commonly called object-oriented programming. This chapter explains objects from the point of view of the.NET Framework. It doesn’t rehash the typical object-oriented theory, because countless excellent programming books cover the subject. Instead, you’ll see the types of objects.NET allows, how they are constructed, and how they fit into the larger framework of namespaces and assemblies. 47 Advanced Web Programming 3.2 THE BASICS ABOUT CLASSES Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods (member function which defines actions) into a single unit. In C#, classes support polymorphism, inheritance and also provide the concept of derived classes and base classes. Generally, a class declaration contains only keyword class, followed by an identifier(name) of the class. But there are some optional attributes that can be used with class declaration according to the application requirement. In general, class declarations can include these components, in order: Modifiers: A class can be public or internal etc. By default modifier of class is internal. Keyword class: A class keyword is used to declare the type class. Class Identifier: The variable of type class is provided. The identifier(or name of class) should begin with an initial letter which should be capitalized by convention. Base class or Super class: The name of the class’s parent (superclass), if any, preceded by the : (colon). This is optional. Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded by the : (colon). A class can implement more than one interface. This is optional. Body: The class body is surrounded by { } (curly braces). Note: Constructors in class are used for initializing new objects. Fields are variables that provide the state of the class and its objects, and methods are used to implement the behavior of the class and its objects. Syntax : //[access modifier] - [class] - [identifier] public class Customer { // Fields, properties, methods and events go here... } 48 48 3.2.1 Objects in C# Types, Objects, And Namespaces It is a basic unit of Object-Oriented Programming and represents the real-life entities. A typical C# program creates many objects, which as you know, interact by invoking methods. An object consists of : State: It is represented by attributes of an object. It also reflects the properties of an object. Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects. Identity: It gives a unique name to an object and enables one object to interact with other objects. Consider Dog as an object and see the below diagram for its identity, state, and behavior. Objects correspond to things found in the real world. For example, a graphics program may have objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as “shopping cart”, “customer”, and “product”. Declaring Objects (Also called instantiating a class) When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behaviour of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances. 49 Advanced Web Syntax: Programming Classname objectname = new classname(); Example 1: using System; public class Student { int id;//data member (also instance variable) String name;//data member(also instance variable) public static void Main(string[] args) { Student s1 = new Student();//creating an object of Student s1.id = 101; s1.name = "Sonoo Jaiswal"; Console.WriteLine(s1.id); Console.WriteLine(s1.name); } } Example 2: Initialize and Display data through method using System; public class Student { public int id; public String name; public void insert(int i, String n) { id = i; name = n; } public void display() { Console.WriteLine(id + " " + name); } } class TestStudent{ 50 50 public static void Main(string[] args) Types, Objects, And Namespaces { Student s1 = new Student(); Student s2 = new Student(); s1.insert(101, "Ajeet"); s2.insert(102, "Tom"); s1.display(); s2.display(); } } 3.2.2 Constructors Constructors are methods that are called when the object is first created. To create an object, the constructor call is preceded by the