dot net framework (using c#)jnujprdistance.com/assets/lms/lms jnu/mca/sem iii... · dot net...

185
Dot Net Framework (Using C#)

Upload: others

Post on 14-Aug-2020

9 views

Category:

Documents


8 download

TRANSCRIPT

Page 1: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

Dot Net Framework (Using C#)

Page 2: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

Board of Studies

Prof. H. N. Verma Prof. M. K. GhadoliyaVice- Chancellor Director, Jaipur National University, Jaipur School of Distance Education and Learning Jaipur National University, JaipurDr. Rajendra Takale Prof. and Head AcademicsSBPIM, Pune

___________________________________________________________________________________________

Subject Expert Panel

Dr. Ramchandra G. Pawar Vaibhav BedarkarDirector, SIBACA, Lonavala Subject Matter ExpertPune

___________________________________________________________________________________________

Content Review Panel

Gaurav Modi Shubhada PawarSubject Matter Expert Subject Matter Expert

___________________________________________________________________________________________Copyright ©

This book contains the course content for Dot Net Framework (Using C#).

First Edition 2014

Printed byUniversal Training Solutions Private Limited

Address05th Floor, I-Space, Bavdhan, Pune 411021.

All rights reserved. This book or any portion thereof may not, in any form or by any means including electronic or mechanical or photocopying or recording, be reproduced or distributed or transmitted or stored in a retrieval system or be broadcasted or transmitted.

___________________________________________________________________________________________

Page 3: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

I

Index

ContentI. ...................................................................... II

List of FiguresII. ........................................................ VII

List of TablesIII. ........................................................VIII

AbbreviationsIV. .........................................................IX

ApplicationV. ............................................................. 164

BibliographyVI. ......................................................... 170

Self Assessment AnswersVII. ................................... 173

Book at a Glance

Page 4: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

II

Contents

Chapter I ....................................................................................................................................................... 1Introduction to C# ........................................................................................................................................ 1Aim ................................................................................................................................................................ 1Objectives ...................................................................................................................................................... 1Learning outcome .......................................................................................................................................... 11.1 Introduction .............................................................................................................................................. 21.2 Brief History of C# Language .................................................................................................................. 21.3 Difference Between C++ and C# ............................................................................................................. 21.4 Difference Between C# and Java ............................................................................................................. 31.5 Object Oriented Programming ................................................................................................................. 31.6 Net Framework ........................................................................................................................................ 31.7 Design Features of C# .............................................................................................................................. 41.8 MSIL(Microsoft Intermediate Language) Code ...................................................................................... 51.9 JIT Compiler ............................................................................................................................................ 61.10 Common Language Specification .......................................................................................................... 61.11 Common Type System ........................................................................................................................... 61.12 Comments .............................................................................................................................................. 71.13 Visual Studio .Net .................................................................................................................................. 71.14 Program Structure of C# ........................................................................................................................ 7 1.14.1 Working without Visual Studio .Net ...................................................................................... 7 1.14.2 With using Visual Studio .Net ................................................................................................ 8 1.14. 3 Understanding our Application Code ................................................................................. 101.15 Namespace in C# ................................................................................................................................. 101.16 Rules .....................................................................................................................................................11Summary ..................................................................................................................................................... 12References ................................................................................................................................................... 12Recommended Reading ............................................................................................................................. 12Self Assessment ........................................................................................................................................... 13

Chapter II ................................................................................................................................................... 15Fundamentals of C# language................................................................................................................... 15Aim .............................................................................................................................................................. 15Objectives .................................................................................................................................................... 152.1 Introduction to Data Types ..................................................................................................................... 162.2 Literals ................................................................................................................................................... 16 2.2.1 C# Supports Two Forms of String Literals ............................................................................ 16 2.2.2 Regular string literals ............................................................................................................. 162.3 Variables ............................................................................................................................................. 16 2.3.1 Rules for Creating Variables .................................................................................................. 172.4 Basic Data Types and their Mapping to CTS ......................................................................................... 17 2.4.1 Value Types ............................................................................................................................ 17 2.4.3 Implicit Data Types ................................................................................................................ 18 2.4.4 Main Features of Simple Types ............................................................................................. 19 2.4.5 Initialising Value Types .......................................................................................................... 19 2.4.6 Reference Types .................................................................................................................... 202.5 Declaration of Variables in C# ............................................................................................................... 21 2.5.1 Value Type Variables .............................................................................................................. 22 2.5.2 Reference Type Variables ....................................................................................................... 22 2.5.3 Constants ............................................................................................................................... 23 2.5.4 Scope of Variables.................................................................................................................. 232.6 Boxing Conversion ............................................................................................................................... 232.7 Unboxing Conversion ........................................................................................................................... 242.8 Operators and Expressions ..................................................................................................................... 25

Page 5: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

III

2.8.1 Arithmetic Operators .............................................................................................................. 25 2.8.2 Relational Operators .............................................................................................................. 26 2.8.3 Logical and Bitwise Operator ................................................................................................ 26 2.8.4 Assignment Operators ............................................................................................................ 262.9 Operator Precedence and Associativity ................................................................................................. 26Summary ..................................................................................................................................................... 28References ................................................................................................................................................... 28Recommended Reading ............................................................................................................................. 28Self Assessment ........................................................................................................................................... 29

Chapter III .................................................................................................................................................. 31Decision Making and Branching .............................................................................................................. 31Aim .............................................................................................................................................................. 31Objectives .................................................................................................................................................... 31Learning outcome ........................................................................................................................................ 313.1 Introduction .............................................................................................................................. 323.2 if statement ............................................................................................................................................. 323.3 if....else statement ................................................................................................................................... 323.4 Switch statement ................................................................................................................................... 343.5 Decision Making and Looping ............................................................................................................... 36 3.5.1 The for Loop .......................................................................................................................... 36 3.5.2 The while Loop ...................................................................................................................... 36 3.5.4 The foreach Loop ................................................................................................................... 383.6 Jump Statements .................................................................................................................................... 39Summary ..................................................................................................................................................... 43References ................................................................................................................................................... 43Recommended Reading ............................................................................................................................. 43Self Assessment ........................................................................................................................................... 44

Chapter IV .................................................................................................................................................. 46Methods in C# ............................................................................................................................................ 46Aim .............................................................................................................................................................. 46Objectives .................................................................................................................................................... 46Learning outcome ........................................................................................................................................ 464.1 Introduction ............................................................................................................................................ 474.2 Declaring Method .................................................................................................................................. 474.3 The Main () Method ............................................................................................................................... 474.4 Invoking Methods .................................................................................................................................. 484.5 Method Parameters ................................................................................................................................ 484.6 Nesting of Methods ................................................................................................................................ 484.7 Methods Parameters ............................................................................................................................... 49 4.7.1 Value Parameters .................................................................................................................... 49 4.7.2 Reference Parameters ............................................................................................................ 49 4.7.3 Output Parameters .................................................................................................................. 49 4.7.4 Parameter Arrays .................................................................................................................... 50 4.7.5 Passing Parameters ................................................................................................................ 50 4.7.6 Passing Value-Type Parameters ............................................................................................. 50 4.7.7 Passing Value Types by Reference ......................................................................................... 51 4.7.8 Swapping Value Types ........................................................................................................... 52 4.7.9 Passing Reference-Type Parameters ...................................................................................... 52 4.7.10 Passing Reference Types by Value ....................................................................................... 52 4.7.11 Passing Reference Types by Reference................................................................................ 534.8 Swapping Two Strings ........................................................................................................................... 54 4.8.1 Pass By Value ......................................................................................................................... 55 4.8.2 Pass By Reference ................................................................................................................. 55

Page 6: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

IV

4.9 In and Out Parameters ............................................................................................................................ 554.10 Variable Arguments List ....................................................................................................................... 564.11 Runtime Evaluation of Argument List ................................................................................................. 574.12 Method Overloading ............................................................................................................................ 594.13 Arrays ................................................................................................................................................... 59 4.13.1 1-D array .............................................................................................................................. 60 4.13.2 Value Type and Reference Type Arrays ............................................................................... 61 4.13.3 Declaring 1-D array ............................................................................................................. 61 4.13.4 2-D array ............................................................................................................................. 61 4.13.5 Array initialisation ............................................................................................................... 61 4.13.6 Declaring Multi-dia Array ................................................................................................... 62 4.13.7 Array-of-arrays (jagged) ...................................................................................................... 624.14 Programming Arrays in C# .................................................................................................................. 624.15 Defining Arrays of Different Types ..................................................................................................... 62 4.15.1 Initialising Arrays ................................................................................................................ 63 4.15.2 Accessing Arrays .................................................................................................................. 63 4.15.3 Array Types .......................................................................................................................... 64 4.15.4 Single Dimension Arrays ..................................................................................................... 64 4.15.4 Multi-Dimensional Arrays ................................................................................................... 64 4.15.5 Jagged Arrays ....................................................................................................................... 66 4.15.6 Mixed Arrays ....................................................................................................................... 674.16 Array Class ........................................................................................................................................... 684.17 Array Properties ................................................................................................................................... 69Summary ..................................................................................................................................................... 70References ................................................................................................................................................... 70Recommended Reading ............................................................................................................................. 70Self Assessment .......................................................................................................................................... 71

Chapter V .................................................................................................................................................... 73Classes and Objects.................................................................................................................................... 73Aim .............................................................................................................................................................. 73Objectives .................................................................................................................................................... 73Learning outcome ........................................................................................................................................ 735.1 Introduction .............................................................................................................................. 745.2 Overview of Classes .............................................................................................................................. 745.3 Programs and Classes: A Quick Example .............................................................................................. 74 5.3.1 Declaring a Class ................................................................................................................... 75 5.3.2 Class Members ....................................................................................................................... 76 5.3.3 Fields ...................................................................................................................................... 76 5.3.4 Explicit and Implicit Field Initialisation ................................................................................ 765.4 Declarations with Multiple Fields .......................................................................................................... 775.5 Methods 775.6 Creating Variables and Instances of a Class........................................................................................... 785.7 Instance Members .................................................................................................................................. 795.8 Access Modifiers .................................................................................................................................... 805.9 Private and Public Access ...................................................................................................................... 815.10 Depicting Public and Private Access ................................................................................................... 81 5.10.1 Example of Member Access ................................................................................................ 81 5.10.2 Accessing Members from Inside the Class .......................................................................... 82 5.10.3 Accessing Members from Outside the Class ....................................................................... 825.11 Putting It All Together .......................................................................................................................... 835.12 Classes and Objects .............................................................................................................................. 84 5.12.1 Classes ................................................................................................................................. 84 5.12.2 Objects ................................................................................................................................. 845.13 Constructors ......................................................................................................................................... 85

Page 7: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

V

5.14 Struct .................................................................................................................................................... 855.15 Static Classes and Static Class Members ............................................................................................ 865.16 Static Classes ....................................................................................................................................... 86 5.16..1 When to Use Static Classes................................................................................................. 86 5.16..2 Static Members ................................................................................................................... 87 5.16. 3 Static Constructors .............................................................................................................. 87 5.16..4 Private Constructors ........................................................................................................... 88 5.16..5 How toWrite a Copy Constructor?...................................................................................... 90 5.16..5 Destructors .......................................................................................................................... 915.17. Member Initialisation .......................................................................................................................... 915.18 The this Reference ............................................................................................................................... 925.19 C# Nested Class ................................................................................................................................... 935.20 Types Versus Instances ......................................................................................................................... 945.21 Constant Members ............................................................................................................................... 945.22 Read Only Member .............................................................................................................................. 955.23 C#’s Const vs. Readonly ...................................................................................................................... 965.24 Properties ............................................................................................................................................. 965.24 Indexers ............................................................................................................................................. 97Summary ..................................................................................................................................................... 99References ................................................................................................................................................. 100Recommended Reading ........................................................................................................................... 100Self Assessment ......................................................................................................................................... 101

Chapter VI ................................................................................................................................................ 103Interfaces .................................................................................................................................................. 103Aim ............................................................................................................................................................ 103Objectives .................................................................................................................................................. 103Learning outcome ...................................................................................................................................... 1036.1 Interface ............................................................................................................................................... 104 6.1.1 Declaring an Interface .......................................................................................................... 107 6.1.2 Implementing an Interface ................................................................................................... 108 6.1.3 Implementing Multiple Interfaces ....................................................................................... 109 6.1.4 References to Multiple Interfaces .........................................................................................110 6.1.5 Accessing Explicit Interface Member Implementations .......................................................111 6.1.6 Operator Overloading ...........................................................................................................1116.2 Overloadable Operators ........................................................................................................................1146.3 Delegates and Events ...........................................................................................................................1166.4 Instance Versus Static Method Targets .................................................................................................1176.5 Generic Delegate Types ........................................................................................................................1176.6 The Func and Action Delegates ............................................................................................................1186.7 Return Type Variance ............................................................................................................................1186.8 Type Parameter Variance for Generic Delegates .................................................................................119Summary ................................................................................................................................................... 124References ................................................................................................................................................. 124Recommended Reading ........................................................................................................................... 124Self Assessment ......................................................................................................................................... 125

Chapter VII .............................................................................................................................................. 127Inheritance and Polymorphism ............................................................................................................. 127Aim ............................................................................................................................................................ 127Objectives .................................................................................................................................................. 127Learning outcome ...................................................................................................................................... 1277.1 Overriding Methods ............................................................................................................................. 1287.2 Abstract Classes ................................................................................................................................... 1287.3 Abstract Methods ................................................................................................................................. 129

Page 8: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

VI

7.4 Sealed Classes ..................................................................................................................................... 1307.5 Preventing Inheritance ......................................................................................................................... 1317.6 Inheritance and Polymorphism ........................................................................................................... 131 7.6.1 Inheritance ........................................................................................................................... 131 7.6.2 Multilevel Inheritance .......................................................................................................... 132 7.5.2 Encapsulation ....................................................................................................................... 134 7.6.3 Polymorphism ...................................................................................................................... 1357.7 Casting and Reference Conversions .................................................................................................... 135 7.7.1 Upcasting ............................................................................................................................. 135 7.7.2 Downcasting ........................................................................................................................ 135 7.7.3 Polymorphism ...................................................................................................................... 1367.8 Polymorphic Programming in .NET .................................................................................................... 1367.9 Casting and Reference Conversions .................................................................................................... 137 7.9.1 Upcasting ............................................................................................................................. 137 7.9.2 Downcasting ........................................................................................................................ 1377.10 The as operator ................................................................................................................................... 1387.11 The is operator .................................................................................................................................... 1387.12 Abstract Classes and Abstract Members .............................................................................. 1397.13 Hiding Inherited Members ................................................................................................................. 1397.14 Sealing Functions and Classes ........................................................................................................... 1397.15 The base Keyword ............................................................................................................................. 1397.16 Constructors and Inheritance ............................................................................................................. 1407.17 Constructor and Field Initialization Order ......................................................................................... 1407.18 Overloading and Resolution .............................................................................................................. 141Summary .................................................................................................................................................. 142References ................................................................................................................................................. 143Recommended Reading ........................................................................................................................... 143Self Assessment ......................................................................................................................................... 144

Chapter VIII ............................................................................................................................................. 146Managing Console I/O Operations ......................................................................................................... 146Aim ............................................................................................................................................................ 146Objectives .................................................................................................................................................. 146Learning outcome ...................................................................................................................................... 1468.1 Introduction .......................................................................................................................................... 1478.2 The Console Class ............................................................................................................................... 1478.3 Console Input ....................................................................................................................................... 1478.4 Console Output .................................................................................................................................... 1488.5 Formatted Output ................................................................................................................................. 1498.6 Numeric Formatting ............................................................................................................................. 150 8.6.1 Standard Numeric Format .................................................................................................... 150 8.6.2 Custom Numeric Format ..................................................................................................... 1518.7 Managing Errors and Exceptions ........................................................................................................ 1518.8 Types of Errors ..................................................................................................................................... 151 8.8.1 Compile-Time Errors .......................................................................................................... 151 8.8.2 Run-Time Errors .................................................................................................................. 1528.9 Debugging in C# .................................................................................................................................. 1538.10 Execution Control .............................................................................................................................. 1538.11 Breakpoints ........................................................................................................................................ 1548.12 Exceptions Syntax of Exception Handling Code ............................................................................... 1568.13 Handling Exceptions .......................................................................................................................... 1578.14 Multiple Catch Statement .................................................................................................................. 158Summary ................................................................................................................................................... 160References ................................................................................................................................................. 161Recommended Reading ........................................................................................................................... 161Self Assessment ......................................................................................................................................... 162

Page 9: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

VII

List of Figures

Fig. 1.1 The .Net framework .......................................................................................................................... 4Fig. 1.2 Overview of CLI ............................................................................................................................... 5Fig. 1.3 MSIL cross language relationship .................................................................................................... 6Fig. 1.4 Visual Studio .Net window ............................................................................................................... 8Fig. 2.1 Copying a value type variable ........................................................................................................ 20Fig. 2.2 Copying a reference type variable .................................................................................................. 21Fig. 2.3 Boxing conversion .......................................................................................................................... 24Fig. 2.4 Boxing and unboxing operation ..................................................................................................... 25Fig. 4.1 Output of mixed array ..................................................................................................................... 68Fig. 5.1 The objects in a running program ................................................................................................... 75Fig. 5.2 Allocating memory for the reference of a class variable ................................................................ 78Fig. 5.3 Allocating memory for the data of a class variable ........................................................................ 79Fig. 5.4 Instance members are distinct between class objects ..................................................................... 80Fig. 6.1 Representation of interface IComparable ..................................................................................... 104Fig. 6.2 Implementing IComparable in MyClass ....................................................................................... 106Fig. 6.3 Class implementing multiple interfaces ........................................................................................110Fig. 6.4 Separate references to different interfaces in the class ..................................................................111Fig. 7.1 ToString() signature ...................................................................................................................... 128Fig. 7.2 Single inheritance ......................................................................................................................... 132Fig. 7.3 Hierarchical inheritance ................................................................................................................ 133Fig. 7.4 Multi-level inheritance ................................................................................................................. 133Fig. 7.5 Hybrid inheritance ........................................................................................................................ 134Fig. 7.6 Multiple inheritance ...................................................................................................................... 134Fig. 8.1 Error list window .......................................................................................................................... 153Fig. 8.2 Debug menu options ..................................................................................................................... 154Fig. 8.3 Debug menu options during debugging mode .............................................................................. 154Fig. 8.4 Breakpoint set ............................................................................................................................... 155Fig. 8.5 Locals window at the breakpoint .................................................................................................. 155Fig. 8.6 Local window after debugging ..................................................................................................... 156

Page 10: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

VIII

List of Tables

Table 1.1 Difference between C++ and C# .................................................................................................... 2Table 1.2 Difference between C# and Java .................................................................................................... 3Table 2.1 Integral data types in C# .............................................................................................................. 18Table 2.2 Floating point data types in C# .................................................................................................... 18Table 2.3 Other data types ........................................................................................................................... 18Table 2.4 Arithmetic operators ..................................................................................................................... 25Table 2.5 Relational operators ..................................................................................................................... 26Table 2.6 Logical and bitwise operators ...................................................................................................... 26Table 2.7 Assignment operators ................................................................................................................... 26Table 2.8 Operators precedence and associativity ....................................................................................... 27Table 3.1 Operator precedence..................................................................................................................... 35Table 6.1 Overloadable operators ...............................................................................................................114Table 8.1 Input/output stream .................................................................................................................... 147Table 8.2 C# Format characters ................................................................................................................. 151

Page 11: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

IX

Abbreviations

BCL - Base Class Library

CLI - Common Language Infrastructure

CLR - Common Language Runtime

CLS - CommonLanguageSpecifications

CTS - Common Type System

FCL - Framework Class Library

FIFO - First In First Out

GUI - Graphical User Interface

IDE - Integrated Development Environment

IDE - Integrated Development Environment

IL - Intermediate Code

JIT - Just In Time

MSIL - Microsoft Intermediate Language

OOP - Object Oriented Programming

PDC - Professional Developers Conference

TCP/IP - Transmission Control Protocol/ Internet Protocol

VB - Visual Basics

XML - Extensible Mark-up Language

Page 12: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

1

Chapter I

Introduction to C#

Aim

The aim of this chapter is to:

introduce fundamentals of C# language•

elucidate object oriented programming•

explain .Net architecture and .Net framework•

Objectives

The objectives of this chapter are to:

explain the concept of OOPs•

explicate .Net framework•

elucidate .Net Framework base class library•

Learning outcome

At the end of this chapter, you will be able to:

understand object oriented programming•

distinguish between C# and other languages•

write programs using Visual Studio .Net•

Page 13: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

2

Dot Net Framework (Using C#)

1.1 IntroductionC#isthefirstcomponentorientedlanguageinC/C++family.Itispronouncedas“SeeSharp”.Itisamulti-purposecomputer programming language. This language is suitable for all kinds of development needs.

C# is basically derived from the C programming language, and it has features such as garbage collection. This featureisverymuchhelpfulforbeginnerstobecomeproficientinC#morequicklythaninCorC++.ToextentC#is similar to Java also, it is object-oriented, and comes with an extensive class library. It supports exception handling, multiple types of polymorphism, and separation of interfaces from implementations.

Compared to other .Net languages a large part of the C# comes with the common .NET Framework API, which provides a large set of classes, including encryption, TCP/IP socket programming, and graphics. Developers can thus write part of an application in C# and another part in another .NET language for example, VB .NET. Keeping the tools, library, and object-oriented development model as it is of object oriented concept only we have to learn the new language syntax for C#.

There are many similarities between C# and the C family of languages, as well as Java, hence a developer with a backgroundinobject-orientedlanguageslikeC++mayfindC#structureandsyntaxintuitive.

1.2 Brief History of C# LanguageThe primary architects of C# were Peter Golde, Eric Gunnerson, Anders Hejlsberg, Peter Sollichy and Scott Wiltamuth. Though, the principal designer of the C# language was Anders Hejlsberg, a lead architect at Microsoft.

C# was designed to be a pure object-oriented programming language. C# debuted in the year 2000 at the Professional Developers Conference (PDC) where Microsoft founder Bill Gates was the keynote speaker. At the same time, Visual Studio .NET was announced.

1.3 Difference Between C++ and C#C++ and C# both are object oriented programming languages but there are some major differences between them, as follows:

C++ C#C++ code usually compiles to assembly language. C# by contrast compiles to Intermediate language (IL),

which has some similarities to java byte code.

It allows multiple inheritance, for instance, it allows a method to be overridden many times in subclasses (derived classes).

Supports inheritance, but not multiple, only 1 override per method/function.

Table 1.1 Difference between C++ and C#

Page 14: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

3

1.4 Difference Between C# and JavaC#classesandjavaclassesarequitesimilarbuttherearefewimportantdifferencebetweenthemregardingconstants,base classes and constructors, static constructors, versioning, accessibility of members, etc. These are as follows:

C# JavaC# uses ‘use constant’ to declare a class constant. Javausesstaticfinaltodeclareaclassconstant.C# supports struct type. Java does not support struct type.C# provides operator overloading Java does not provide operator overloading.InC#,thebasememberisrequiredtohavethevirtualkeywordandthederivedmemberisrequiredtousethe override keyword.

In Java, class members are virtual by default and method having the same name in a derived class overrides the base class members.

C# provides built-in delegates and events. Java uses interfaces and inner classes to achieve a similar result.

Table 1.2 Difference between C# and Java

1.5 Object Oriented ProgrammingObject-Oriented Programming (OOP) is a programming paradigm which uses objects – data structures which consist ofdatafieldsandmethodstogetherwiththeirinteractions–todesignapplicationsandcomputerprograms.

OOP include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance.

Many modern programming languages today support OOP, at least as an option. Object-oriented programming (OOP) represents an attempt to make programs more closely model.

An object-oriented programming language such as C# includes a number of features that make it very different from a procedural language.

1.6 Net FrameworkThe Microsoft .Net Framework is a software technology that is available with several Microsoft windows operating systems. It includes a large library of pre-coded solutions to common programming problems and a virtual machine that manages the execution of program.

Page 15: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

4

Dot Net Framework (Using C#)

Our .Net Applications(WinForms, Web Applications, Web Services)

Data (ADO.Net) and XML Library

Framework Class Library (FCL)(IO,Streams,Sockets,Security,Reflection,UI)

Common Language Runtime (CLR)(Debugger, Type Checking, JIT, exceptions, GC)

Windows OS

Fig. 1.1 The .Net framework

1.7 Design Features of C#Following are the main design features of C# language.

InteroperabilityDescribes methods to interoperate between C# managed code and unmanaged code.•Describes how to use indexed properties to access COM properties that have parameters.•Interopservices and System.Enterpriseservices namespace of framework; access to other functionality is provided •using the P/Invoke feature.

Common Language Runtime EngineThe Common Language Runtime (CLR) is the virtual machine component of Microsoft’s .NET framework.•It is responsible for managing the execution of .NET programs.•All programs written for the .NET framework, regardless of programming language, are executed by the •CLR.

Base Class LibraryThe Base Class Library (BCL) is a standard library available to all languages using the .NET Framework.•BCLprovidesclasseswhichencapsulatealargenumberofcommonfunctions,suchasfilereadingandwriting,•graphic rendering, database interaction, and XML document manipulation.

Simplified DeploymentInstallation of computer software must be carefully managed to ensure that it does not interfere with previously •installedsoftware,andthatitconformstosecurityrequirements.

Page 16: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

5

The.NETframeworkincludesdesignfeaturesandtoolsthathelpsaddresstheserequirements.•

SecurityThedesignismeanttoaddresssomeofthevulnerabilities,suchasbufferoverflows,thathavebeenexploited•by malicious software.Additionally, .NET provides a common security model for all applications.•

PortabilityThe design of the .NET Framework allows it to theoretically be platform agnostic and thus cross-platform •compatible.That is, a program written to use the framework should run without change on any type of system for which •the framework is implemented.

Net Framework lies within the Common Language Infrastructure (CLI). The core aspect of the .Net framework is CLI. The purpose of the CLI is to provide a language-neutral platform for application development and execution, including functions for exception handling, garbage collection, security, and interoperability. Microsoft’s implementation of the CLI is called the Common Language Runtime or CLR.

Followingfiguregivestheoverviewofcommonlanguageinfrastructure:

C# code

Compiler Compiler Compiler

VB.net code

J# code

Common Language Runtime

Common Intermediate

Language

01001100101011, 11010101100110

Compiler, Common Language Infrastructure

.Net Compatible Languages compile to a second platform-natural language called Common Intermediate

Language (CIL),

TheplatformspecificCommonLanguageRuntime(CLR) compiles CIL to machine readable

code that can be executed on the current platform.

Fig. 1.2 Overview of CLI

1.8 MSIL(Microsoft Intermediate Language) CodeWhen we compile our .Net program using any .Net compiler language example, C#, VB.Net or C++.Net our source code does not get converted into the executable binary code, but to an intermediate code known as MSIL which is interpreted by the Common Language Runtime.

Page 17: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

6

Dot Net Framework (Using C#)

MSIL is operating system and hardware independent code. Upon program execution, this MSIL (intermediate code) is converted to binary executable code (native code). Cross language relationships are possible as the MSIL code is similar for each .Net language.

Followingfigureshowsthecrosslanguagerelationship.

Code in any .NetLanguage

MSILCode

ExecutableNative Code

compile time

LanguageCompiler

Just In TimeCompiler

run time

Fig. 1.3 MSIL cross language relationship

1.9 JIT CompilerJIT stands for ‘Just in Time’ compiler. It is the integral part of CLR. It converts the MSIL code to executable Native code and executes the batch of code Just in Time. Which get cache and next time when the code gets executed from cache in stud of compiling again.

The execution process of program in above figure is as follows:CLR class loader lodes MSIL code and metadata are loaded into memory.•The code manager calls the entry point method which is Win Main or DLL Main method. •The JIT compiler compiles the method before its execution of the entry point method.•The code manager places the objects in memory and controls the execution of the code.•The garbage collector performs periodic checks on the managed heap to identify the objects which is not in •use for the application.

At the time of program execution the type checker ensures that all objects and values, and the references of objects and values has its valid type. The type checker also makes sure that only valid operations are performed on the code otherwise the exception will be thrown. The code is controlled by CLR at run time.

CLR enforces security in following manner.It controls and accesses the system recourses like hard disk.•It controls and accesses the network connections.•It controls and accesses the other hard ware resources.•

1.10 Common Language SpecificationWhatisCommonLanguageSpecification?

CLS makes a language a ‘.Net compliant’ language.•Microsofthasreleasedasmallsetofspecificationsthateachlanguageshouldmeettoqualifyasa.Netcompliant•language.CLS basically addresses language design issues and lays down certain standard.•If the program code is written in CLS boundary, the code is guaranteed to be usable in any other .Net •framework.

1.11 Common Type SystemWhat is a Common Type System?

.Netalsodefinesacommontypesystem(CTS).•Like CLS, CTS is also a set of standards.•

Page 18: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

7

CTSdefinethebasicdatatypesthatILunderstands.•Each .Net compliant language should map its data types to these standard data types.•It makes possible for two languages to communicate with each other.•

1.12 CommentsComments are the Programmer’s text to explain the code. These are ignored by the compiler and are not included inthefinalexecutablecode.

C# uses syntax for comments that is similar to java and C++.•The text following double slash marks (//any comment) are line commands. •The comment ends with the end of the line.•

Syntax: //This is my main method of program static void Main() { ... }

1.13 Visual Studio .NetMicrosoft Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop console and graphical user interface applications along with Windows Forms applications, web sites, web applications, and web services in both native code together with managed code for all platforms supported by Microsoft Windows, Windows Mobile, Windows CE, .NET Framework, .NET Compact Framework and Microsoft Silverlight.

1.14 Program Structure of C#Follow the procedure below to build the .Net program with and without using Visual Studio .Net.

1.14.1 Working without Visual Studio .NetOpen notepad, or any other text editor, and write the following code•

using System;

namespace MyHelloWorldApplication

{

class HelloWorld

{

static void Main(string[] args)

{

Console.WriteLine("Hello World");

}

}

}

Page 19: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

8

Dot Net Framework (Using C#)

Savethiswithanyfilenamewiththeextension“.cs”.Example:‘MyFirstApplication.cs’•

Tocompilethisfile,gotocommandpromptandwrite:•

csc MyFirstApplication.cs

Thiscompilestheprogramandcreatesan.exefile(MyFirstApplication.exe)inthesamedirectory.•Also reports any errors that may occur.•to run program, type:•

MyFirstApplication

This will print Hello World as a result on the console screen.•

1.14.2 With using Visual Studio .Net

Start Microsoft Visual .Net and select File-New-Project.•Itshowstheopenfiledialog,selectVisualC#projectfromprojecttypeandselectConsoleApplicationfrom•Template.Write MyHelloWorldApplication in the name text below and click OK.•

Fig. 1.4 Visual Studio .Net window

Page 20: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

9

It will show the initial default code for our hello world application as follows:

Remove the documentation comments (lines starting with///).•Change the name of the Class1 to HelloWorld and write.•

Console.WriteLine("Hello World"); in place of //TODO: Add code....

Page 21: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

10

Dot Net Framework (Using C#)

The code will look as follows:

using System;

namespace MyHelloWorldApplication

{

class HelloWorld

{

[STAThread]

static void Main(string[] args)

{

Console.WriteLine("Hello World");

}

}

}

Now to compile and execute the application, select Debug-Start without debugging or press Ctrl+F5.•Open a new Console window with Hello World written in it.•The window gets close once any key is pressed, terminating the program.•

1.14.3 Understanding our Application CodeThe program which we have written above processes as follows:

Thefirstlineofourprogram(usingSystem;)appearsinvirtuallyalltheC#programs.•It gives access to the core functionality of computer system.•The second line of our code (namespace MyHelloWorldApplication) means.•

1.15 Namespace in C#Namespaces provide scope, or an enclosing context, for the namesdefinedwithin the group. It has followingfeatures:

A namespace is simply a logical collection of related classes in C#.•Namespaces are the way that .NET avoids name clashes between classes.•Theyaredesignedtoavoidthesituationinwhichyoudefineaclasstorepresentanemployee,nameyourclass•employee,andthensomeoneelsedoesthesamething(quitealikelyscenario–theproportionofbusinessesthathaveemployeeseemstobequitehigh).

So, in the second line of our program we are declaring that the following classes (within {} block) are part of MyHelloWorldApplication namespace

Page 22: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

11

namespace MyHelloWorldApplication

{

...

}

1.16 RulesFollowingrulesshouldbefollowedwhiledefiningnamespaces:

C# namespace have no physical mapping as in the case java.•Classes with same namespace can be in different folders.•The C# concept of mapping is similar to packages in java and namespace in standard C++.•The namespace may contain classes, events, exceptions, delegates and even other namespaces called ‘Internal •namespace’.

Internal namespace can be defined as follows:

namespace Parent { namespace Child { ... } }

Theseinternalnamespacescanbedefinedlikethis:

Page 23: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

12

Dot Net Framework (Using C#)

SummaryC# is a multi-purpose computer programming language.•The primary architects of C# were Peter Golde, Eric Gunnerson, Anders Hejlsberg, Peter Sollichy and •Scott Wiltamuth, though the principal designer of the C# language was Anders Hejlsberg, a lead architect at Microsoft.C++ and C# can be distinguished on the basis of compiler and inheritance.•Also,C#classesandjavaclassesarequitesimilarbuttherearefewimportantdifferencesbetweenthemregarding•constants, base classes and constructors, static constructors, versioning, accessibility of members etc.Object-OrientedProgramming(OOP)isaprogrammingparadigmusing“objects”–datastructureswhichconsists•ofdatafieldsandmethodstogetherwiththeirinteractions–todesignapplicationsandcomputerprograms.The Microsoft .Net Framework includes a large library of pre-coded solutions to common programming problems •and a virtual machine that manages the execution of program.The main design features of C# language are Interoperability, Common Language Runtime Engine, Base Class •Library,SimplifiedDeployment,Security,Portability.MSIL is operating system and hardware independent code. Upon program execution, this MSIL (intermediate •code) is converted to binary executable code (native code).JIT Compiler stands for ‘Just in Time’ Compiler. It is the integral part of CLR.•CLS makes a language a ‘.Net compliant’ language. Like CLS, CTS is also a set of standards.•Comments are the Programmer’s text to explain the code.•Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft.•A namespace is simply a logical collection of related classes in C#.•

ReferencesTheazon.com, 2011. • Top 10 most popular programming language. [Online] Available at: <http://theazon.com/2011/10/top-10-most-popular-programming-language/> [Accessed 24 January 2011].Bizhostnet. • Microsoft .NET Framework. [Online] Available at: <http://www.bizhostnet.com/pg_frame-net-hosting.html> [Accessed 24 January 2011]Grip, J., 2003. • C# Programming tutorial (1of2). [Video Online] Available at: <http://www.youtube.com/watch?v=NC5s__B6WVQ> [Accessed 24 January 2011]C# • Video Programming Tutorials Episode 1: Gathering The Tools We Need. [Video Online] Available at: <http://www.youtube.com/watch?v=wYP-ruzN8SQ> [Accessed 24 January 2012]. Oberg, R. J., 2002. • C# Using .NET, Prentice Hall PTR Publication.Gunnerson, E., 2001. • A programmer’s introduction to C#, 2nd ed., Apress Publication.

Recommended ReadingPurdum, J., 2008. • C# 3.0 An Introduction to Object Oriented Programming, Wrox Publication.Watson, B., 2010. • C# 4.0 How-To, Pearson Education.Bako, P., 2010. • Introduction to C#, Createspsce Publication.

Page 24: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

13

Self Assessment

C# uses _________ to declare a class constant.1. use constanta. constantb. numeric constantc. character constantd.

Which are the design features of C# language?2. Interoperabilitya. Base class library b. Securityc. characterstuffingd.

Which of the following statements is true?3. Classes with same namespace can be in different folders.a. Classes with same namespace cannot be in different folders. b. Classes in same namespace should be in same folder.c. One folder should contain classes with same namespace. d.

.Net application includes which of the following?4. Win formsa. Web applicationb. Web servicesc. All of the aboved.

____________describes how to use indexed properties to access COM properties that have parameters.5. Securitya. Base class libraryb. Interoperabilityc. Simplifieddeploymentd.

_______ is operating system and hardware independent code.6. CLRa. CLS b. MSILc. ILd.

____________ does not provide operator overloading.7. Javaa. C#b. C++c. C d.

Page 25: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

14

Dot Net Framework (Using C#)

A namespace is simply a logical collection of related ________ in C#.8. objectsa. classesb. methodsc. datad.

The __________ places the objects in memory and controls the execution of the code.9. code detectora. code managerb. memory managementc. program executiond.

Microsoft Visual Studio is an _______from Microsoft.10. IDEa. CLRb. CLSc. CTSd.

Page 26: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

15

Chapter II

Fundamentals of C# language

Aim

The aim of this chapter is to:

introduce data types, literals and variables•

elucidate boxing and unboxing convention•

explain operators and their precedence•

Objectives

The objectives of this chapter are to:

explain value type and reference type•

explicate how arithmetic operators react given different kinds of data•

elucidate the power of programming•

Learning outcome

At the end of this chapter, you will be able to:

identify the applications to perform programming•

enlist the rules for creating variables •

distinguish between various operators•

Page 27: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

16

Dot Net Framework (Using C#)

2.1 Introduction to Data TypesAdatatypeisasetofdata.Datatypeshavevalueswithpredefinedcharacteristics.Examplesofdatatypesare:integer,floatingpointunitnumber,character,string,andpointer.Datatypesdecidehowthevaluesareprocessedbythecomputer,andhowtheywillgetstoredinthememory.However,thelanguagespecifiestherangeofvaluesfor a given data type. In the object-oriented programming, a programmer is allowed to create new data types as per therequirementoftheapplication.

2.2 LiteralsA literal is a source code representation of a value. A variable’s value can change but literals cannot be changed. Literals can be formed using numbers, characters, and combinations of characters in the program. They can be assigned to a variable or used in an expression.

Example-The number 11 is always 11.The character A is always A. The value of a literal can be copied into a variable and then that variable can change; the process does not change the value of the original literal. It is also possible to useliteralswithoutassigningthemtoaspecificvariable.

2.2.1 C# Supports Two Forms of String LiteralsC# supports two forms of literals explain as follows.

2.2.2 Regular string literals

Aregularstringliteralconsistsofzeroormorecharactersenclosedindoublequotes,forexample,“hello”.•Itmayalsoincludebothsimpleescapesequences(suchas\tforthetabcharacter)andhexadecimalandUnicode•escapesequences.

Verbatim string literalVerbatimstringliteralconsistsofan‘@’characteranditshouldbewrittenfollowedbyadouble-quotecharacter,•zeroormorecharacters,andaclosingdouble-quotecharacter.Example:@”hello”.In a verbatim string literal, the characters between the delimiters are interpreted verbatim; the only exception •foritisaquote-escape-sequence.Inparticular,simpleescapesequencesandhexadecimalandUnicodeescapesequencesarenotprocessedin•verbatim string literals.A verbatim string literal may span multiple lines.•

If we are declaring a variable in the C# language, that means we are actually initialising a class and an object gets created. Consider the example below:

int homeWorkScore1;int examNumber1;int numberOfPointsScored;

Here, we have declared three variables of int type in each line, hence we are initialising the class three times and three int objects are created here. Literals are often used to give a value to an object’s data portion. This can be done when the object is created or later in the program statements. A value such as 100 could be assigned to homeWorkScore1 using the following statement: homeWorkScore1 = 100; Here 100 is a numeric literal. The contents of the memory location where the variable homeWorkScore1 stored the value 100 can be changed; however, the literal value of 100 cannot be changed. 100 is always 100.

2.3 VariablesDuring the execution of program, data is temporarily stored in the memory. A variable is the name given to a memory location holding a particular type of data. So each variable has associated with a data type and a value.

Page 28: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

17

Variables are declared as follows:

<data type> <variable>;

For example:int i;

2.3.1 Rules for Creating VariablesFor creating the variables, some rules have to be followed, these are as follows:

Variables should be declared before using them.•Integer type values reserves 4 bytes in the memory.•Itisreferredbytheidentifier‘i’intheprogram.•Variables can be initialised as we declare it in the program and also declare/initialise multiple variables of the •same type in a single statement.Variablenameshouldbedefinedbylowercaseletters.•

Example:

bool isReady = true;

float percentage = 87.88, average = 43.9;

char digit = '7';

2.4 Basic Data Types and their Mapping to CTSThe CTS types falls into two main categories:

Value types •Reference types (objects, delegates)•

2.4.1 Value TypesValue types are known as structures. Value type mainly supports implicit data types, structs and enumeration. Value types are passed to methods by passing an exact copy while Reference types are passed to methods by passing only theirreference(handle).Implicitdatatypesaredefinedinthelanguagebytheprogrammer,whileexplicitdatatypesare types that are made by using or composing implicit data types. Implicit data types in .Net compliant are mapped totypesintheCommonTypeSystem(CTS)andCLS(CommonLanguageSpecification).Hence,eachimplicitdatatype in C# has its corresponding .Net type.

Table below gives the implicit data types in C#:

Page 29: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

18

Dot Net Framework (Using C#)

Integral type

C# Type .Net type Size in Bytes Descriptionbyte Byte 1 May contain integers from 0 to 255sbyte SByte 1 Signed byte from -128 to 127short Int16 2 Ranges from -32,768 to 32,767ushort UInt16 2 Unsigned, ranges from 0 to 65,535int(default) Int32 4 Ranges from -2,147,483,648 to 2,147,483,647uint UInt32 4 Unsigned, ranges from 0 to 4,294,967,295long Int64 8 Ranges from -9,223,327,036,854,775,808 to

9,223,372,036,854,775,807ulong UInt64 8 Unsigned, ranges from 0 to

18,446,744,073,709,551,615

Table 2.1 Integral data types in C#

Floating point typeFloat Single 4 Ranges from ±1.5×10-45 to ±3.4×1038 with 7 digits precision.

Requiresthesuffix‘f’or‘F’Double(default) Double 8 Ranges from ±5.0×10-324 to ±1.7×10308 with 15-16 digits

precision.

Table 2.2 Floating point data types in C#Other typesBool Boolean 1 Contains either true or falseChar Char 2 ContainsanysingleUnicodecharacterenclosedinsinglequotationmarksuchas‘c’decimal Decimal 12 Ranges from ±1.0×10-28 to ±7.9×1028 with28-29digitsprecision.Requiresthesuffix

‘m’ or ‘M’

Table 2.3 Other data types

2.4.2 Implicit Data TypesImplicitreferstoauserdefinedkeywords.Ithasapowertoacceptanyreasonableconvertibledatatypewithouttype casting it. Following are features of implicit data types:

Implicit data types are represented in language using keywords, so each of the above is a key word in C#.•Keywordsarethewordsdefinedbythelanguageandcannotbeusedasidentifiers.•String is nothing but an implicit data type in C#, so string is a keyword in C#.•Implicitdatatypesarevaluetypesandthusstoredonthestack,whileuserdefineddatatypesorreferenced•types are stored using the heap.AstackisadatastructurethatstoreitemsinaLastInfirstout(LIFO)fashion.•It is an area of memory supported by the processor and its size is determined at the compile time.• A heap consists of memory available to the program at run time. •

Reference types are allocated using memory available from the heap dynamically (during the execution of program). The garbage collector searches for non reference data in heap during the execution of program and returns that space to operating system.

Page 30: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

19

The value types consist of two main categories:Structs•Enumerations•

Structs fall into these categories:Numeric types•Integral types•Floating-point types•decimal•bool•Userdefinedstructs•

Variables are based on value types which directly contain values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself. All value types are derived implicitly from the System.ValueType. Unlike with reference types, you cannot derive a new type from a value type. However, like reference types, structs can implement interfaces. Unlike reference types, a value type cannot contain the null value. However, the nullable types feature does allow for values types to be assigned to null. Each value type has an implicit default constructor that initialises the default value of that type. 2.4.3 Main Features of Simple TypesAll of the simple types those who are integral to the C# language are of the .NET Framework System Types. For example, int is an alias of System.Int32. Constant expressions, whose operands are all simple type constants, are evaluated at compilation time. Simple types can be initialised by using literals. For example, ‘A’ is a literal of the type char and 100 is a literal of the type int.

2.4.4 Initialising Value TypesLocal variables in C# must be initialised before they are used. A local variable can be declared without initialisation as follows:int myInt;

We cannot use it before initialisation, but we can use it as follws:

myInt = new int(); // Invoke default constructor for int type.

Thisstatementisequivalenttothefollowingstatement:

myInt = 0; // Assign an initial value, 0 in this example.

Also we can have the declaration and the initialisation in the same statement as follows:

int myInt = new int();Or int myInt = 0;Usingthenewoperatorcallsthedefaultconstructorofthespecifictypeassignsthedefaultvaluetothevariable.Intheexamplegivenabove,thedefaultconstructorassignedthevalue0tomyInt.Ifwearedefiningourownconstructerwithuser-definedtypes,thenusenewtoinvokethedefaultconstructor.Forexample,thefollowingstatementinvokes

Page 31: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

20

Dot Net Framework (Using C#)

the default constructor of the Point struct:Point p = new Point ( ); // Invoke default constructor for the struct.

Afterthiscall,thestructisconsideredtobedefinitelyassigned;thatis,allitsmembersareinitialisedtotheirdefaultvalues.

2.4.5 Reference Types When a reference type is assigned to a variable, the variable does not contain the contents of the object directly. Instead of it, the object’s data is constructed in memory and the variable contains a reference to that memory location. Ifasecondvariableisassignedthevalueofthefirst,acopyofthereferenceismade.Thetwovariablesnowcontainindependent copies of the reference but in each case the reference points towards the same data. If the properties of suchanobjectarechanged,thechangeisapparentthroughbothreferences.Thisissameastheemailingoffilesasattachments. A user may have a word-processed document that another user wishes to edit. This document can be emailed to the second user as an attachment. Either user can now modify the document in any way without affecting the other’s copy.

The diagram below illustrates what happens when a value type variable is copied:

int a= 72

int b

int b = a;

a b

72

72 72

7275

Fig. 2.1 Copying a value type variable

Follow the steps below to understand the procedure in the above figure.Inthefirststep,thevariable“a”isdeclaredandassignedavalueof72.•First column explains the value becoming the content of the variable.•Inthesecondstep,thevariable“b”isdeclaredandassignedthevaluefromvariable“a”.•This value is copied into the contents of the new variable, as can be seen in the second column.•Inthethirdstep,thevalueinvariable“a”ismodified.Thevalueinvariable“b”isunchangedbecausethis•variable contains an independent copy of the value. The two variables are not linked in any way.Variables of reference types, referred to as objects, store references to the actual data. This section introduces •the following keywords used to declare reference types:Class•Interface•delegate•

Following built-in reference types are also included in this:dynamic•object•string•

Page 32: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

21

Thisprocedureissameasemailingoflinkstofiles.Ausermayhaveaword-processeddocument,heldinanetworkfolderthatanotheruserwishestoread.Theusercanemailalinktothefiletoanotheruser.Bothusersnowhaveareferencetothedocumentintheformofalinktothefileinthesharedfolder.Boththeusercanclickthelinkand edit the text but the link itself remains unchanged. If the other user clicks his copy of the link, he will see the updated document.

Followingfigureillustrateswhathappenswhenreferencetypeavariableiscopied.

Person a= new Person( );

a.Height= 72

Person b= a

a.Height= 75

a b

x

x

x

x x

x

x

72

72

75

Fig. 2.2 Copying a reference type variable

Followthestepsbelowtounderstandtheprocedureintheabovefigure:Inthefirststep,theobject“a”isdeclaredasaninstanceofthePersonclass.Thisisasimpleclasswithasingle•property representing the person’s height in inches. Anewareainmemory,representedbythe“X”column,isallocatedtoholdtheobject’scontents.•Currentlythecontentsarenullbecausethepropertyhasnotbeenset.Thevariable“a”holdsareferencetothe•memorylocation“X”.Inthesecondstep,theHeightpropertyofvariable“a”issetto72.Thecontentsofthefirstcolumnareunmodified•because the reference itself has not changed. However, the memory location holding the height property is changed as given in the third column.•Inthethirdstep,asecondPersonvariable“p”isdeclaredandassignedthevalueofvariable“a”.•Asthesearereferencetypes,thereferencetothe“X”memorylocationiscopiedintovariable“b”.•Both variables have a reference to the same underlying location and both now return a Height property of 72.•Inthefinalstep,theHeightpropertyofvariable“a”ischangedto75.Thisdoesnotmodifythereferencewithin•thevariable,onlythecontentsofthememoryholdingtheproperty,seeninthe“X”column.As both variables still reference that memory location, both variables will return a Height property of 75.•

2.5 Declaration of Variables in C#In C# all variables must be declared before they are used. In the declaration a data type and a name for the variable mustbespecified.Itallowsthememorytosetasideforthevariable.Anoptionalinitialvaluecanbeincludedwiththe declaration if you know what the value should be to start.Syntax for variable declaration[scope] [=initial value];

Page 33: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

22

Dot Net Framework (Using C#)

DescriptionThe scope determines the accessibility of the variable (public, local, private) and the default is private. The data typespecifieswhatkindofdatathevariablewillhold.Optionallythevariablecanbeinitialisedtoaspecificvalue.All variables must be initialised giving a value to it, before they are used in any calculation. If the variables are not initialised, the compilation of the program will fail.

2.5.1 Value Type VariablesValue type variables are also known as stack variables because they are stored on the stack. Value type variables can be directly declared and referenced. As the variables go out of scope, they are removed from the stack, ensuring the proper destruction of the variables. As the variables are created on the stack, they should not be initialised; that is the responsibility of the program. The use of an uncapitalised variable will result in a compiler error. For example, Value variable.

Syntax for the value-type variableInt n; //uncapitalised intLong l = 327 //initialised longFloatf=3.13F;//floatinitialisedfromsingle-precisionliteral

2.5.2 Reference Type VariablesReference type variables are made up of two parts: the reference on the stack and the object on the heap. The creation of the object and the reference to the object is commonly known as the instantiation of the object. For example Reference variable.

Syntax for the reference-type variablestring strMimico;city objToronto = null;object objGeneric;

Initialisation of variablesDeclaration of variables is must before using them in any object oriented language like C#. Also, there is a concept of“DefiningAssignment”inC#accordingtowhich“localvariablesmustbeinitialisedbeforebeingused”.Localvariablesmeansvariablesdefinedinamethod.

The following program will not compile because the variable age is not declared,

static void Main()

{int age;// age = 18;

Console.WriteLine(age); // error

}

But, if the second line is uncommented, the program will compile. C# does not assign default values to local variables. C# is also a type safe language, i.e. values of particular data type can only be stored in their respective (or compatible) data type. We can not store integer values in boolean data types and vice-versa like we used to do in C/C++.

2.5.3 Constants Constantsarefixvalueswhichareknownatcompiletimeandremainsconstantthroughouttheprogram,thatis,itsvaluecannotbechange.Constantsaredeclaredwiththeconstmodifier.OnlytheC#built-intypes(excludingSystem.

Page 34: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

23

Object)maybedeclaredasconst.User-definedtypes,includingclasses,structs,andarrays,cannotbeconst.Wecanusethereadonlymodifiertocreateaclass,struct,orarraythatisinitialisedonetimeatruntime(forexampleinaconstructor) and thereafter cannot be changed. C# does not support const methods, properties, or events. The enum typeenablesyoutodefinenamedconstantsforintegralbuilt-intypes,forexample,int,uint,long,andsoon).

Constants should also be initialised as they are declared. Consider the following example:class Calendar1{ public const int months = 12;}

In the above example, the constant months is always 12, and it cannot be changed even by the class itself. When thecompilerencountersaconstantidentifierinC#sourcecode(forexample,months),itsubstitutestheliteralvaluedirectly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constantatruntime,constfieldscannotbepassedbyreferenceandcannotappearasanl-valueinanexpression.

2.5.4 Scope of VariablesAll the variables that we are using in the program should be declare at the start of the Main () method. C# allows a local variable to be declared within any block. A block begins with an opening curly brace and ended by a closing curlybrace.Ablockdefinesadeclarationspace,orscope.Thus,eachtimewhenanewblockisstarted,newscopeiscreated automatically. A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects. To understand the effect of nested scopes, consider the following program:

//Demonstrate block scopeUsing System;Class ScopeDemo{public static void Main(){int x; // known to all code within Main()x=10;if(x==10){// start new scopeint y=20; // known only to this block// x and y both known hereConsole.WriteLine(“xandy:”+x+“”+y);x=y*2;}// y=100; // Error! Y not known here // x is still known hereConsole.WriteLine(“xis“+X);}}

2.6 Boxing Conversion Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a Value Types. To the type object or to any interface type implemented by this value type C# gives reference. Boxing a value type allocates an object instance on the heap and copies the value into the new object.Value type variables should be declared as follows:int i = 123;

Page 35: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

24

Dot Net Framework (Using C#)

Consider example below to understand the boxing operation on the variable i:object o = i; // implicit boxing

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables,iando,isillustratedinthefollowingfigure.

On the stack On the Heapi

int i= 123;

object o=i;

o (i boxed)int123

Fig. 2.3 Boxing conversion Examplebelowexplainsthefigure2.3andgivestheperformanceofexplicitboxingasfollows:int i = 123;object o = (object)i; // explicit boxing

An integer variable i gets converted to an object o by means of boxing. Then, the value stored in the variable i is changed from 123 to 456. The example shows that the original value type and the boxed object use separate memory locations, and therefore can store different values.

class TestBoxing{ static void Main() { int i = 123; object o = i; // implicit boxing

i = 456; // change the contents of i

System.Console.WriteLine(“Thevalue-typevalue={0}”,i);System.Console.WriteLine(“Theobject-typevalue={0}”,o); }}

OutputThe value-type value = 456The object-type value = 123

2.7 Unboxing Conversion Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:

Checking the object instance to make sure it is a boxed value of the given value type.•Copying the value from the instance into the value-type variable.•

Both the boxing and unboxing operations can be demonstrated with the following example:int i = 123; // a value typeobject o = i; // boxing

Page 36: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

25

int j = (int)o; // unboxing

Figure below gives the result of both the operations together,

On the stack On the Heapi

int i= 123;

object o=i;

int j=(int) o;

o

o

(i boxed)int123

Fig. 2.4 Boxing and unboxing operation

2.8 Operators and ExpressionsC# provides a range of operators for the purpose of creating mathematical expressions.

2.8.1 Arithmetic OperatorsThese operators primarily fall into the category of binary operators in that they take two operands. The exception is the unary negative operator (-) which serves to indicate that a value is negative rather than positive. This contrasts with the subtraction operator (-) which takes two operands that is one value to be subtracted from another. For example:int x = -10; // Unary - operator used to assign -10 to a variable named xx = y - z; // Subtraction operator. Subtracts z from y

The following table lists the primary C# arithmetic operators:

Operator Description-(unary) Negates the value of a variable or exprestion

* Multiplication/ Division+ Addition- Subtraction% Modulo++ Increment by 1-- Decrement by 1

Table 2.4 Arithmetic operators

Page 37: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

26

Dot Net Framework (Using C#)

2.8.2 Relational OperatorsRelational operators are used for comparison purpose in conditional statements.C# has following relational operators:

Operand Description== Equalitycheck!= Un-equalitycheck> Greater than< Less than

>= Greaterthanorequalto<= Lessthanorequalto

Table 2.5 Relational operators

2.8.3 Logical and Bitwise OperatorThese operators are used for logical and bitwise calculations.C# contains following logical and bitwise operator:

Operand Description& Bitwise AND Bitwise OR∧ Bitwise XOR! Bitwise NOT

&& “Logical”or“shortcircuit”AND “Logical”or“shortcircuit”OR

Table 2.6 Logical and bitwise operators

2.8.4 Assignment OperatorsAssignment operators are use to assign values to variables.Some common assignment operators in C# are:

Operand Description

= Simple assignment+= Subtractive assignment-= Multiplicative assignment*= Division assignment/= Division assignment

%= Modulo assignment

Table 2.7 Assignment operators

2.9 Operator Precedence and AssociativityThere are certain rules to ensure the outcome of the C# expression for evaluating it. These rules are governed by precedence and associativity and preserve the semantics of all C# expressions. Precedence refers to the order in whichoperationsshouldbeevaluated.Subexpressionswithhigheroperatorprecedenceareevaluatedfirst.

Page 38: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

27

There are two types of associativity:Left•Right•

Operators with left associativity are evaluated from left to right, and operator with right associativity, is evaluated from right to left. For example, the assignment operator is right-associative. Therefore, the expression to its right is evaluated before the assignment operation is invoked.

Table below shows the C# operators, their precedence, and associativity.

Operator Associativityx, y f(x) a[x] x++ x-- new type of default checked/unchecked delegate Left

+(unary) –(unary) ~ ++X –X (T)x Left*/% Left

+(arithmetic) –(arithmetic) Left<< >> Left

< > <= >= is as Left== != Left

$ Left∧ Left Left

&& Left Left?: Right

*= /= %= += -= <<= >>= &= ∧= = Right

Table 2.8 Operators precedence and associativity

Page 39: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

28

Dot Net Framework (Using C#)

SummaryAdatatypeisasetofdata.Datatypeshavevalueswithpredefinedcharacteristics.•Data types decide how the values are processed by the computer, and how they will get stored in the memory.•A variable’s value can change but literals cannot be changed.•During the execution of program, data is temporarily stored in the memory. A variable is the name given to a •memory location holding a particular type of data.Implicitreferstoauserdefinedkeywords.Ithasapowertoacceptanyreasonableconvertibledatatypewithout•type casting it.All of the simple types those who are integral to the C# language are of the .NET Framework System Types. •For example, int is an alias of System.Int32.Local variables in C# must be initialised before use also local variable cannot be declared without •initialisation.When a reference type is assigned to a variable, the variable does not contain the contents of the object •directly.Boxing is used to store value types in the garbage-collected heap.•Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value •type that implements the interface.There are certain rules to ensure the outcome of the C# expression for evaluating it. These rules are governed •by precedence and associativity and preserve the semantics of all C# expressions.Operators with left associativity are evaluated from left to right.•Operator with right associativity, is evaluated from right to left.•

ReferencesRasheed, F., 2006, • Programmer’s Heaven C# School. Synchron Data publication.Balagurusamy, E., 2008, • Programming in C#, 2nd ed., Tata McGraw-Hill.Dot Net Pearls., • C# Multiple Local Variable Declarations [Online] Available at: <http://www.dotnetperls.com/multiple-local-variable> [Accessed 27 December 2012].Black,Wasp., • C# Value Types and Reference Types. [Online] Available at: <http://www.blackwasp.co.uk/ValueReferenceTypes.aspx> [Accessed 27 December 2012].shamma1, 2008. • Introduction to C#, [Video Online] Available at: <http://www.youtube.com/watch?v=J95GdnHsn9s> [Accessed 27 December 2012].ProgrammingVideos, 2008. • C# Tutorial - 01 - Introduction to C#, [Video Online] Available at: <http://www.youtube.com/watch?v=aJoeeHT8zdA>[Accessed 27 December 2012].

Recommended ReadingAlbahari, J. and Albahari, B., C# 4.0 Pocket Reference, O’really Publication.•Stellman, A. and Green, J., Head First C#, O’really Publication.•Mayo, J., C# 3.0 Unleased, 2nd ed., SAMS Publication.•

Page 40: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

29

Self Assessment

__________ decide how the values are processed by the computer, and how they will get stored in the 1. memory.

literals a. variablesb. stringc. data typesd.

Itisalsopossibletouse________withoutassigningthemtoaspecificvariable.2. data typesa. literalsb. operatorsc. variablesd.

The syntax for variable declaration is3. [scope] [=initial value];a. Int n; //uncapitalised intb.

Long l = 327//initialised long

Floatf=3.13F;//floatinitialisedfromsingle-precisionliteral

string strMimico;city objToronto = null;object objGeneric;c. initial value = [scope];d.

Boxing is used to store_________ in the garbage-collected heap.4. data typea. reference typeb. null typec. value typed.

Match the column 5. C# Type Size in Byte1. byte A.42. short B. 83. int C. 24. long D. 1

1-A, 2-C, 3-D, 4-Ba. 1-D, 2-C, 3-A, 4-Bb. 1-D, 2-C, 3-A, 4-Bc. 1-B, 2-A, 3-C, 4-Dd.

Which of the following statement is true?6. The operator ?: has rightmost associativity.a. The operator ?: has leftmost associativity.b. The operator ?: has no associativity.c. The operator ?: has middle associativity.d.

Page 41: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

30

Dot Net Framework (Using C#)

Structs fall into which of the following categories?7. Numeric typesa. Int typesb. Float typec. Static type d.

Which of the following statements is true?8. A reference type cannot be assigned to a variable.a. A reference type is assigned to a variable, when a variable contains the object directly.b. When a reference type is assigned to a variable, the variable does not contain the contents of the object c. directly.When a reference type is assigned to a variable, the variable contains the contents of the object directly.d.

A __________consist of memory available to the program at run time9. static a. externb. heapc. variabled.

Find odd man out10. <a. = =b. >=c. +d.

Page 42: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

31

Chapter III

Decision Making and Branching

Aim

The aim of this chapter is to:

introduce the concept of various decision making statements•

elucidate development of programs using operators•

explain various loops and their syntax•

Objectives

The objectives of this chapter are to:

explain jump statements and their use•

study order of operators and their precedence•

elucidate the power of loops in the programming•

Learning outcome

At the end of this chapter, you will be able to:

write programs using various loops•

identify the of use jump statements to reduce the length of the program•

understand conditional operator statements•

Page 43: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

32

Dot Net Framework (Using C#)

3.1 IntroductionA C# program is a set of statements that are normally executed in the order written by a programmer. When the options or repetitions of certain calculations are not necessary the order is followed by the compiler. In some conditions programmerhavetochangetheorderofexecutionofprogramorrepeatagroupofstatementsuntilcertainspecifiedconditions are met. To see whether the particular condition has met or not decision-making statements are use. This invokes the computer to direct execute certain statements accordingly.

Whenaprogrambreaksthesequentialflowofexecutionandjumpstoanotherpartoftheprogram,itiscalledasbranching. When a branching is based on a particular condition, it is known as conditional branching. If branching takes place without any decision, it is known as unconditional branching.

C# language processes such decision-making capabilities and supports the following statements known as control or decision-making statements.

If statement•Switch statement•Conditional operator statement•

3.2 if statementTheifstatementisapowerfuldecision-makingstatementandisusedtocontroltheflowofexecutionofstatements.It is two-way decision statement and is used in conjunction with an expression. It takes the following form.If (expression)

Itallowsthecomputertoevaluatetheexpressionfirstandthen,dependingonwhetherthevalueoftheexpression(relation or condition) is true or false, it transfers the control to a particular statement. The program at this point has twopathstofollow,oneforthetrueandtheotherforthefalseconditionasshowninthefigure:

The if statement selects a statement for execution based on the value of a Boolean expression. It takes the following form:

if (expression) statement1[else statement2]where:

expression

An expression that can be implicitly converted to bool or a type that contains overloading of the true and false operatorsstatement1

The embedded statement(s) to be executed if expression is truestatement2

The embedded statement(s) to be executed if expression is false

3.3 if....else statementThe if statement selects a statement for execution based on the value of a Boolean expression. In the following example, the Boolean variable result is set to true and then checked in the if statement. The output is: The variable is set to true.

Page 44: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

33

bool result = true;

if (result){Console.WriteLine(“Thevariableissettotrue.”);}else{Console.WriteLine(“Thevariableissettofalse.”);}

Iftheexpressionintheparenthesisisevaluatedtobetrue,thentheConsole.WriteLine(“Thevariableissettotrue.”);statement is executed. After executing the if statement, control is transferred to the next statement. The else is not executed in this example.

If you wish to execute more than one statement, multiple statements can be conditionally executed by including them into blocks using {} as in the example above.

The statement(s) to be executed upon testing the condition can be of any kind, including another if statement nested into the original if statement. In nested if statements, the else clause belongs to the last if that does not have a corresponding else. For example:

int x = 12;int y = 18;

if (x > 10) if (y > 20)Console.Write(“Statement_1”); elseConsole.Write(“Statement_2”);

In this example, Statement_2 will be displayed if the condition (y > 20) evaluates to false. However, if you want to associate Statement_2 with the condition (x >10), use braces:

if (x > 10){ if (y > 20)Console.Write(“Statement_1”);}elseConsole.Write(“Statement_2”);

In this case, Statement_2 will be displayed if the condition (x > 10) evaluates to false

ExampleIn this example, you enter a character from the keyboard and the program checks if the input character is an alphabetic character. If so, it checks if it is lowercase or uppercase. In each case, the proper message is displayed.

Page 45: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

34

Dot Net Framework (Using C#)

3.4 Switch statementThe switch statement is a control statement that handles multiple selections by passing control to one of the case statements within its body. It takes the following form:

switch (expression){ case constant-expression: statement jump-statement [default: statement jump-statement]}Where:

expressionAn integral or string type expressionstatement

The embedded statement(s) to be executed if control is transferred to the case or the defaultjump-statement

A jump statement that transfers control out of the case bodyconstant-expression

Controlistransferredtoaspecificcaseaccordingtothevalueofthisexpression.

The Ternary ?: OperatorAlso called the conditional operator, the ternary operator ? : provides another way to express a simple if…else selectionstatement.Theoperatorconsistsofaquestionmark?andacolon:.Thegeneralformatforthisconditionalexpression is:expression1? expression2:expression3;

Theexpressionthatcomesbeforethequestionmark,expression1,isevaluatedfirst.Whenexpression1evaluatesto true, expression2, following the questionmark, is executed; otherwise expression3, following the colon, isexecuted.

An example of a statement using the conditional operator is as follows:grade=examScore>89?’A’:’C’;

This reads if examScore is greater than 89, assign A to grade ; otherwise, assign C tograde.

WhenexamScorehasavalueof75,thefirstexpression,examScore>89,evaluatestofalse;thus,expression3,C,following the colon is executed, and C is assigned to the grade memory location. It performs the same operation as:

If (examScore>89)grade=’A’;elsegrade=’C’;

Page 46: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

35

The conditional operator is often used in an assignment statement.

Most service companies have a minimum charge they use for making house calls. For example, a washing machine repair person. He may charge $50.00 per hour; however, his minimum charge for travelling to your home is $100.00.Thus, when it takes him less than two hours, the charge is $100.A conditional expression to calculate the charges follows:

double charges,timeAtSite=3.5;charges=timeAtSite<2.0?100.00:timeAtSite*50.00;

Thevaluestoredinchargeswouldbe175.Thefirstexpression(timeAtSite<2.0)evaluatestofalse;thus,thelastexpression (timeAtSite * 50.00) is evaluated and 175 is stored in charges. The ternary conditional operator is not as readable as the if statement. The if statement is used more often than other forms of the selection statement.

Order of operationsWhen an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. For example, an expression such as value1 + value2 * value3 is evaluated as value1 + (value2 * value3) because the * operator has higher precedence than the + operator. In table given below, the operators used primarily for arithmetic were presented.

Table below adds the operators presented in this chapter.

Category Operator PrecedenceUnary + - ! ~ ++x –x Highest

Multiplicative */ %Additive + -

Relational < > <= >=Equality == !=

Logical AND &Logical OR |

Conditional AND &&Conditional OR ||

Conditional ?:Assignment = *= /= %= += -= Lowest

Table 3.1 Operator precedence

The operators listed in the above table appear from highest to lowest precedence. Except for the assignment operators, all binary operators are left-associative, meaning that operations are performed from left to right. For example, aValue + bValue – cValue is evaluated as (aValue + bValue) – cValue

The assignment operators and the conditional operator ? : are right-associative, meaning that operations are performed fromrighttoleft.Forexample,firstValue=secondValue=thirdValueisevaluatedasfirstValue=(secondValue=(thirdValue)). Precedence and associativity can be controlled using parentheses. It is not necessary to include the parentheses in the previous example because the order of operations of the language determines the order. Parentheses can certainly be added to increase readability, but they are not necessary.

The actual order in which the operations are performed is given following the declaration and conditional expression in the following example.

Page 47: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

36

Dot Net Framework (Using C#)

intvalue1=10,value2=20,value3=30,value4=40,value5=50;if(value1>value2||value3==10&&value4+5<value5)Console.WriteLine(“Theexpressionevaluatestotrue”);

The preceding expression is evaluated in the following order:1. (value4+5) (40 + 5) 45

2. (value1>value2) (10 > 20) false

3. ((value4+5) <value5) (45 < 50) true

4. (value3==10) (30 == 10) false

5. ((value3==10) && ((value4+5) < value5)) false && true false

6. ((value1>value2) || ((value3==10) && ((value4+5) <value5)))

false || false false

Because the expression evaluates to false, the line following the if statement is skipped or bypassed.The executable statement after the Console.WriteLine( ) would be the next one performed after the expression is evaluated.

3.5 Decision Making and LoopingFollowing are various types of loops used in C#

3.5.1 The for LoopA for loop works like a while loop, except that the syntax of the for loop includes initialisation and condition modification.forloopsareappropriatewhenyouknowexactlyhowmanytimesyouwanttoperformthestatementswithin the loop. The contents within the for loop parentheses hold three sections separated by semicolons (<initialiser list>; <boolean expression>; <iterator list>) {<statements>}.

The initialiser list is a comma separated list of expressions. These expressions are evaluated only once during the lifetime of the for loop. This is a one-time operation, before loop execution. This section is commonly used to initialise an integer to be used as a counter.

Once the initialiser list has been evaluated, the for loop gives control to its second section, the boolean expression. There is only one boolean expression, but it can be as complicated as you like as long as the result evaluates to true or false. The boolean expression is commonly used to verify the status of a counter variable.

When the boolean expression evaluates to true, the statements within the curly braces of the for loop are executed. After executing for loop statements, control moves to the top of loop and executes the iterator list, which is normally used to increment or decrement a counter. The iterator list can contain a comma separated list of statements, but is generally only one statement. Listing 4-3 shows how to implement a for loop. The purpose of the program is to print only odd numbers less than 10.

Listing 4-3. The For Loop: ForLoop.cs

using System;

class ForLoop

Page 48: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

37

3.5.2 The while LoopThe two looping structures described in the previous parts of the C# Fundamentals tutorial are similar in operation. Inmostcases,theforloopandtheforeachloopwillexecuteforadefinednumberofiterationscontrolleddirectlybytheprogrammerorbythenumberofitemsinacollection.Insomesituationsthenumberofrequirediterationsisnot known and cannot be estimated because the loop should continue until a condition is met. This type of program flowcanbeachievedusingthewhileloop.Thewhileloopallowstoindicate‘whileaconditionistrue,loopthroughthe following command(s).

The syntax for the statement is:while (condition) command;

The condition element is any predicate. When the value is true, the command provided executes. The command may be a single statement or a code block surrounded by brace characters {}. The following example uses the while loop to calculate the powers of three between one and one thousand. Unless we have calculated the number of iterations beforehand, we cannot use a for loop to achieve this so a while loop is used instead.

int current = 1;string output = String.Empty;

// Loop while the value being checked is 1000 or less while (current <= 1000){output+=current.ToString()+““; current *= 3;}

Console.WriteLine(output);//Outputs“1392781243729“

The while loop’s condition is checked each time the looping code is about to be processed. If the condition is false forthefirstiteration,thebodyoftheloopwillneverexecute.Inthefollowingexample,thebodyoftheloopisignored:

int current = 1001;string output = String.Empty;

// Loop while the value being checked is 1000 or less while (current <= 1000){output+=current.ToString()+““; current *= 3;}

Console.WriteLine(output);//Outputs“”

3.5.3 The Do-While LoopThedo-whileloopallowsyoutoindicate“dothisprocesswhileaconditionistrue”.Thesyntaxforthestatementis similar to the while loop but reverses the positioning of the condition and the command:do command while (condition);

The principle of the do-while loop is the same as for the while loop. Whilst the condition is true, the command or block of commands is executed. However, because the condition is checked after each iteration of the loop, the code within the loop is guaranteed to run at least once.

Page 49: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

38

Dot Net Framework (Using C#)

The following example shows a do-while loop used to calculate a factorial.int value = 1;int factorial = 10;

do{ value *= factorial; factorial--;} while (factorial > 1);

Console.WriteLine(value);//Outputs“362{ public static void Main() { for (int i=0; i < 20; i++) { if (i == 10) break;

if (i % 2 == 0) continue;

Console.Write(“{0}“,i); } Console.WriteLine(); }} for each statement

3.5.4 The foreach LoopA foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, which can be found in the System.Collections namespace. The syntax of a foreach loop is foreach (<type> <iteration variable> in <list>) {<statements>}. The type is the type of item contained in the list. For example, if the type of the list was int [] then the type would be int.

The iterationvariable isan identifier thatyouchoose,whichcouldbeanythingbutshouldbemeaningful.Forexample, if the list contained an array of people’s ages, then a meaningful name for item name would be age.

Theinkeywordisrequired.

While iterating through the items of a list with a foreach loop, the list is read-only. This means that you can’t modify the iteration variable within a foreach loop..

Oneachiterationthroughaforeachloopthelistisqueriedforanewvalue.Aslongasthelistcanreturnavalue,thisvalue will be put into the read-only iteration variable, causing the statements in the foreach block to be executed. Whenthecollectionhasbeenfullytraversed,controlwilltransfertothefirstexecutablestatementfollowingtheend of the foreach block. Listing below demonstrates how to use a foreach loop.

Page 50: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

39

The ForEach Loop: ForEachLoop.cs

using System;

class ForEachLoop{ public static void Main() {string[]names={“Cheryl”,“Joe”,“Matt”,“Robert”};

foreach (string person in names) {Console.WriteLine(“{0}“,person); } }} jumps in loops.

3.6 Jump StatementsWhentheflowofcontrolreachesjumpstatements,programexecutionisunconditionallytransferredtoanotherpart of the program. Following are the types of jump statements:

breakThe switch statement, mentioned previously, showed one way to use the break statement. It allows program control to jump out of the switch statement. Similarly, the break statement allows jumping out of any decision or loop. Its destinationisalwaysthefirststatementfollowingthemostcontainingdecisionorloop.

The following example shows two ways to break out of a loop:stringdoAgain=“Y”;

while(doAgain==“Y”)

{

Console.Write(“PleaseEnterSiteName:“);

siteName[count++] = Console.ReadLine();

Console.Write(“AddAnother?:“);

doAgain = Console.ReadLine();

if (count >= 5)

{

break;

}

}

Normally,ausertypesYtocontinueortypesanythingelsetoleave.However,anarrayisaspecifiedsizeanditwouldn’tbenicetoattempttooverflowitsbounds,becausethiswouldcauseanerror.Theifstatementispresenttoguard against this happening. When the number of entries in the array exceeds its max capacity, the program breaks out of the loop with the break statement. The break statement goes only to the next level below its enclosing loop.

Page 51: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

40

Dot Net Framework (Using C#)

continuecontinue statements are used in loops. They allow a program to jump immediately to the Boolean expression of the loop. Here’s a program snippet that shows how to use a continue statement to discontinue processing during a given iteration:

foreach(string site in siteName){if(response.ToUpper()==“Y”&&site != null &&site.IndexOf(filter)==-1){continue;}Console.WriteLine(“\t{0}”,site);}

Thisexamplechecksthecurrentarrayentryagainstapredefinedfilter.TheIndexOf()method,apredefinedstringfunction,returnsa–1ifthevalueoffilterdoesnotexistinthesitestring.Whenthevalueis–1,thecontinuestatementis invoked. This sends program control back to the top of the foreach loop for another iteration.

returnreturn statements return statements allow jumping out of a method or, in the case of the Main() method, the program. The following example shows how the return statement is used in the Main() method:

public static int Main(string[] args){// other program statementsreturn 0;}

TheMain()methodhasareturntypeofint,asspecifiedbytheintdeclarationinfrontofthewordMain.Ifthereturnvalue were void, there would be two choices: Don’t use the return statement, or just use the statement return; with no value. Because the example returns an int, the return statement must return an integer value. Therefore, when this program runs without problems and ends, it returns a value of 0 to the command line. All methods have return types and have the same return statement options as shown previously. The difference is that the value is returned to the statement making the method call.

gotoThe goto statement allows unconditional branching to another program section. The form of the goto statement is as follows:

goto label;The destination is marked by a label. Legal destinations include the current level of the goto statement or outside of the current loop. The following code shows how a goto statement could be used:do {// some processingwhile (/* some Boolean condition */){// some processingfor (int i=0; i < someValue; i++){

Page 52: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

41

if (/* some Boolean condition */){gotoquickExit;}}}} while (/* some Boolean condition */);

quickExit:

The above example displays a potential scenario where the code is deeply nested in processing. If a certain condition causes the end of processing to occur in the middle of that loop, the program has to make several less-than-graceful checks to get out. The example shows how using a goto might be helpful in making a clean exit from a tricky situation. It might even make the code easier to read, instead of trying to design a clumsy workaround. Again, the decisiontouseagotoisbasedontherequirementsaprojectneedstomeet.

A goto may never jump into a loop. Here’s an example that should help you visualise just how illogical such an attempt might be:

// won’t compilewhile (/* some Boolean condition */){// some processinginnerLoop:// more processing}goto innerLoop;

It’s normally desirable to have some type of initialisation and control while executing a loop. This scenario could easily violate the integrity of any loop, which is why it is not allowed.

throwThethrowstatementinC#signifiestheoccurrenceofanexceptionduringtheexecutionofaprogram.Duringtheexecution of a program, if the program encounters a throw statement, the program terminates and returns the errors. Themostcommonwayofusingthethrowstatementistouseitwiththetry...catch...finallystatement.Whenanexception is thrown, the program looks for the catch statement that handles the exception.

Syntax for the throw statement:Throw [expression];

Now, let’s create a console application named ThrowStatement to demonstrate the use of the throw statement. Perform the following steps to do this:

click start ->All programs -> Microsoft Visual Studio 2008 to open the visual studio 2008 IDE �In the visual studio 2008 IDE, select File ->New ->Project from the menu bar to open the new project �dialog box.In the new project dialog box, select visual C# ->windows in the project types pane and the console �Application option in the template plane.Enter throw statement in the Name text box to specify the name of the application, and specify an appropriate �location for the application in the Location box.

Page 53: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

42

Dot Net Framework (Using C#)

Click Ok button. The ThrowStatement application is created. �Intheprogram.csfile,addthecodegiveninListing �

ProgramStatic void main(string[ ] args){ Int number; Console.Write(“Enteranumber:”); Number= int.Parse(Console.ReadLine( )); Try { If (number > 10) ThrownewException(“MaximumLimitis10”); }Catch (Exception e){Console.WriteLine(“Exceptionhasbeenoccur”);

}Finally{ Console.WriteLine(“Thisisthelaststatement”);

Console.Write(“\nPressEntertoquit...”); Console.ReadLine( );}}

Press F5 key to run the application.

Page 54: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

43

SummaryA C# program is a set of statements that are normally executed in the order written by a programmer.•When the options or repetitions of certain calculations are not necessary the order is followed by the •compiler.The switch statement is a control statement that handles multiple selections by passing control to one of the •case statements within its body.The ternary operator ? : provides another way to express a simple if…else selection statement.•A foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, •which can be found in the system.Oneachiterationthroughaforeachloopthelistisqueriedforanewvalue.•Thebreakstatementallowsjumpingoutofanydecisionorloop.Itsdestinationisalwaysthefirststatement•following the most containing decision or loop.When the number of entries in the array exceeds its max capacity, the program breaks out of the loop with the •break statement.The return statements allow jumping out of a method or, in the case of the Main() method, the program.•The goto statement allows unconditional branching to another program section.•It’s normally desirable to have some type of initialisation and control while executing a loop.•ThethrowstatementinC#signifiestheoccurrenceofanexceptionduringtheexecutionofaprogram.•During the execution of a program, if the program encounters a throw statement, the program terminates and •returns the errors.Themostcommonwayofusingthethrowstatementistouseitwiththetry...catch...finallystatement.•

ReferencesBalagurusamy E., 2008. • Programming in C#, Tata McGraw Hill.Sempf, B., Sphar, C., Davis, S. and Sphar, C., 2010. • C# 2010 for Dummies, Wiley Publishing, Inc.Chromatophore, 2008. • Decision Making and Branching, [Online] Available at: <http://mycblog.org/index.php?option=com_content&view=article&id=47&Itemid=66 > [Accessed 31 January 2012].Mayo, J., 9 February 2011, • The C# Station Tutorial, [Online] Available at: <http://www.csharp-station.com/Tutorials/Lesson04.aspx> [Accessed 31 January 2012].csharpdemos, 2011. • C# Tutorial 16 - The Foreach Loop, [Video Online] Available at: <http://www.youtube.com/watch?v=ypgRaSsnq7w>[Accessed3February2012].MillionIT, 2011. • Tutorial 13: C# (C Sharp): foreach loop, [Video Online] Available at: <http://www.youtube.com/watch?v=KDrcj5XiwC0> [Accessed 3 February 2012].

Recommended ReadingDixit, J. B., 2005.• Fundamentals of Computing, Laxmi Publications (P) LTD.James, F., 2003. • Teach Yourself Visual C# >NET 2003, 1st ed., SAMS Publication.Rama Krishna Rao, B., 2007. • C# Concepts And Practice, Prentice-Hall publication.

Page 55: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

44

Dot Net Framework (Using C#)

Self Assessment

When the options or repetitions of certain calculations are not necessary the order is followed by the 1. ___________.

interpretera. locatorb. compilerc. command promptd.

The if statement selects a statement for execution based on the value of a ___________expression.2. conditionala. booleanb. parameter c. throwd.

Which operator has the lowest precedence?3. *=a. &&b. >=c. !d.

The goto statement allows ____________branching to another program section.4. conditionala. nestedb. unconditionalc. hierarchicald.

Which of the following statements is false?5. Whentheflowofcontrol reaches jumpstatements,programexecution isunconditionally transferred toa. another part of the program.The goto statement allows unconditional branching to another program section.b. A foreach loop is used to iterate through the items in a list.c. The if statement is used to jump the control to the end of the program.d.

Syntax for the throw statement is6. Expressiona.

{throw;

}throw [expression];b. expression [throw];c. throwd. {

Expression;

}

Page 56: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

45

The general format for this conditional expression is? 7. expression1 ?: expression2 ?: expression3;a. expression 2: expresion3 ? expression1;b. expression1? expression2: expression3;c. expresion3 ?: expresion1: expression 2;d.

The most common way of using the throw statement is to use it with 8. thetry...catch...finallystatement.a. The go to statementb. The while loopc. The else if statementd.

Match the column9. Operator Category1. == != A. Additive2. < > <= >= B. Conditional3. + - C.Equality4. ?: D. Relational

1-C, 2-D, 3-A, 4-Ba. 1-A, 2-B, 3-C, 4-Db. 1-D, 2-A, 3-B, 4-Cc. 1-B, 2-C, 3-D, 4-Ad.

Which of the following statement is false?10. *= % = += are assignment operatorsa. * / % are multiplicative operatorsb. + - ! ~ are unary operatorsc. == ! = are relational operatorsd.

Page 57: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

46

Dot Net Framework (Using C#)

Chapter IV

Methods in C#

Aim

The aim of this chapter is to:

introduce various methods in C#•

elucidate invoking methods and nesting of methods•

explain arrays and types of arrays•

Objectives

The objectives of this chapter are to:

explain method parameters•

describe array class properties•

elucidate method overloading•

Learning outcome

At the end of this chapter, you will be able to:

write programs using nested methods and arrays•

identify various types of arrays•

understand pass by value and pass by reference•

Page 58: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

47

4.1 IntroductionA method is a block of code containing a series of statements. In C#, every executed instruction is done so in the context of a method. A program causes the statements to be executed by calling the method and specifying any requiredmethodarguments.TheMainmethodistheentrypointforeveryC#applicationanditiscalledbythecommon language runtime (CLR) when the program is started.

4.2 Declaring MethodMethods are declared within a class or struct by specifying the access level, the return value, the name of the method, and any method parameters. Method parameters are surrounded by parentheses, and separated by commas. Empty parenthesesindicatethatthemethodrequiresnoparameters.IntheexamplebelowclassMotorcyclecontainsthreemethods:

class Motorcycle{

public void StartEngine() { }public void AddGas(int gallons) { }public int Drive(int miles, int speed) { return 0; }

}

Callingamethodonanobjectissimilartoaccessingafield.Aftertheobjectname,addaperiod,thenameofthemethod, and parentheses. Arguments are listed within the parentheses, and separated by commas. The methods of the Motorcycle class can therefore be called like this:

Motorcycle moto = new Motorcycle();moto.StartEngine();moto.AddGas(15);moto.Drive(5, 20);

4.3 The Main () MethodEvery C# application must contain a single Main method specifying where program execution is to begin. In C#, Main is capitalised, while Java uses lowercase main. Main can only return int or void, and has an optional string array argument to represent command-line parameters:

static int Main(string[] args){//...return 0;}

The string array parameter that contains any command-line arguments passed in works just as in Java. Thus, args[0] specifiesthefirstcommand-lineparameter,args[1]denotesthesecondparameter,andsoon.UnlikeC++,theargsarraydoesnotcontainthenameoftheEXEfile.TheMainmethodistheentrypointofourprogram,wherewecreate objects and invoke other methods. There can only be one entry point in a C# program. Study the following program to learn this:class TestClass{

static void Main(string[] args){

// Display the number of command line arguments:System.Console.WriteLine(args.Length);

}}

Page 59: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

48

Dot Net Framework (Using C#)

OverviewThe Main method is the entry point of your program, where the program control starts and ends.

It is declared inside a class or struct. It must be static and it should not be public. (In the example above it •receives the default access of private.)It can either have a void or int return type.•The Main method can be declared with or without parameters.•Parameters can be read as zero-indexed command line arguments.•UnlikeCandC++,thenameoftheprogramisnottreatedasthefirstcommandlineargument.•

4.4 Invoking MethodsInvoking methods in C# contains different methods, explain as follows.

Control.Invoke Method (Delegate)Executesthespecifieddelegateonthethreadthatownsthecontrol’sunderlyingwindowhandle.

Namespace: System.Windows.FormsAssembly: System.Windows.Forms (in System.Windows.Forms.dll)Syntax:public Object Invoke ( Delegate method)

4.5 Method ParametersA method parameter should be written in type System.Delegate as follows.

Type: System.DelegateA delegate that contains a method to be called in the control’s thread context.

Return ValueReturn value for method is of type, Type: System.Object

The return value from the delegate being invoked, or it returns nothing if the delegate has no return value.

Delegates that contains a method has various characteristics:Delegates are similar to function pointers in C or C++ languages.•Delegates encapsulate a reference to a method inside a delegate object. •The delegate object can then be passed to code that calls the referenced method, and the method to be invoked •can be unknown at compile time. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and more secure.•

4.6 Nesting of MethodsWhen a C# method is called by another method of the same class is known as nesting of methods. Calling a method from another method of same class can be invoked without creating the class object and dot operator. The nested sequenceofC#methodsenablestoexecutethegroupofcodestatementsonastacktoprocessthesameinputdataandreturnthefinaloutput.

Page 60: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

49

Example for Nesting of C# Methods

def MyMethod():1.

print ‘Hello from a method.’

def MyInnerMethod(): print ‘Hello from a nested method.’

MyInnerMethod()

2) static void Main(){Console.WriteLine(“Hellofrommain.”);

Func<int, int> NestedMethod = (x) => {Console.WriteLine(“Innestedmethod.Valueofxis{0}.”,x); return x; };

int result = NestedMethod(3);}

4.7 Methods ParametersThe method parameter contains four kinds of formal parameters:

Valueparameters,whicharedeclaredwithoutanymodifiers.•Referenceparameters,whicharedeclaredwiththerefmodifier.•Outputparameters,whicharedeclaredwiththeoutmodifier.•Parameterarrays,whicharedeclaredwiththeparamsmodifier.•

4.7.1 Value ParametersValueparameterisalsocalledInparameter.Aparameterdeclaredwithnomodifiersisavalueparameter.Avalueparameter corresponds to a local variable that gets its initial value from the corresponding argument supplied in the method invocation. A method is permitted to assign new values to a value parameter. Such assignments only affect the local storage location represented by the value parameter. They have no effect on the actual argument given in the method invocation.

4.7.2 Reference ParametersAparameterdeclaredwitharefmodifierisareferenceparameter.Contrastinglytovalueparameter,areferenceparameter does not make a new storage location. Instead, a reference parameter represents the same storage location as the variable given as the argument in the method invocation. Within a method, a reference parameter is always considereddefinitelyassigned.

4.7.3 Output ParametersAparameterdeclaredwithanoutmodifier isanoutputparameter.Similar toa referenceparameter, anoutputparameter does not create a new storage location. Instead, an output parameter represents the same storage location as thevariablegivenastheargumentinthemethodinvocation.Everyoutputparameterofamethodmustbedefinitelyassigned before the method returns. Output parameters are typically used in methods that produce multiple return values.

Page 61: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

50

Dot Net Framework (Using C#)

4.7.4 Parameter ArraysAparameterdeclaredwithaparamsmodifierisaparameterarray.Ifaformalparameterlistincludesaparameterarray, it must be the last parameter in the list and it must be of a single-dimensional array type. For example, the types string[] and string[][] can be used as the type of a parameter array, but the type string[,] cannot. It is not possible to combinetheparamsmodifierwiththerefandoutmodifiers.

4.7.5 Passing ParametersParameters can be passed either by value or by reference. Passing parameters by reference allows function members which are methods, properties, indexers, operators, and constructors to change the value of the parameters. It holds that change to continue. To pass a parameter by reference, we use the ref or out keyword.

Parameter passing is done by various methods as follows:Passing Value-Type Parameters•Passing Reference-Type Parameters•

It also includes the following examples in table 4.1:

Example Demonstrate Uses ref or out1 Passing value types by value No2 Passing value types by reference Yes3 Swapping value types (two integers) Yes4 Passing reference types by value No5 Passing reference types by reference Yes6 Swapping reference types (two strings) Yes

Table 4.1 Examples of parameter passing

4.7.6 Passing Value-Type ParametersA value-type variable contains its data directly where as reference-type variable do not contain it but it contains a reference to its data. Therefore, passing a value-type variable to a method means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the variable. If we want the called method to change the value of the parameter, we should pass it by reference, using the ref or out keyword.

For example: Passing Value Types by Value

The following example demonstrates passing value-type parameters by value. The variable myInt is passed by valuetothemethodSquareIt.Anychangesthattakeplaceinsidethemethodhavenoaffectontheoriginalvalueof the variable.

// PassingParams1.cs using System;class PassingValByVal{

staticvoidSquareIt(intx)// The parameter x is passed by value.// Changes to x will not affect the original value of myInt.{x *= x;Console.WriteLine(“Thevalueinsidethemethod:{0}”,x);

Page 62: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

51

}public static void Main()

{int myInt = 5;Console.WriteLine(“Thevaluebeforecallingthemethod:{0}”,myInt);SquareIt(myInt);//PassingmyIntbyvalue.Console.WriteLine(“Thevalueaftercallingthemethod:{0}”,myInt);}}

Output for the program above is:The value before calling the method: 5The value inside the method: 25The value after calling the method: 5

The above program executes step by step as follows:The variable myInt, being a value type, contains its data (the value 5). •WhenSquareItisinvoked,thecontentsofmyIntarecopiedintotheparameterx,whichissquaredinsidethe•method. InMainthevalueofmyIntisthesame,beforeandaftercallingtheSquareItmethod.•The change that takes place inside the method only affects the local variable x.•

4.7.7 Passing Value Types by ReferencePassing value type by Reference is same as parameter only the value of the parameter is changed after calling the method instead of passing the parameter using the ref keyword.

For example, // PassingParams2.cs using System;class PassingValByRef{staticvoidSquareIt(refintx)// The parameter x is passed by reference.// Changes to x will affect the original value of myInt.{x *= x;Console.WriteLine(“Thevalueinsidethemethod:{0}”,x);}public static void Main(){int myInt = 5;Console.WriteLine(“Thevaluebeforecallingthemethod:{0}”,myInt);SquareIt(refmyInt);//PassingmyIntbyreference.Console.WriteLine(“Thevalueaftercallingthemethod:{0}”,myInt);}}

Page 63: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

52

Dot Net Framework (Using C#)

Output for the code is:The value before calling the method: 5The value inside the method: 25The value after calling the method: 25

Code detailsIn this example, it is not the value of myInt that is passed; rather, a reference to myInt is passed. •The parameter x is not an int; it is a reference to an int (in this case, a reference to myInt).•Whenxissquaredinsidethemethod,whatactuallygetssquarediswhatxrefersto:myInt.•

4.7.8 Swapping Value TypesA common example of changing the values of the passed parameters is the Swap method, where you pass two variables, x and y, and have the method swap their contents. You must pass the parameters to the Swap method by reference; otherwise, we will be dealing with a local copy of the parameters inside the method. The following is an example of the Swap method that uses reference parameters:

static void SwapByRef(ref int x, ref int y){ int temp = x; x = y; y = temp;}When you call this method, use the ref keyword in the call, like this:

SwapByRef (ref i, ref j);

4.7.9 Passing Reference-Type ParametersA variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to the reference, such as the value of a class member. However, we cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. Follow the method below to do so in which we have pass the parameter using the ref (or out) keyword.

4.7.10 Passing Reference Types by ValueThe following example demonstrates passing a reference-type parameter, myArray, by value, to a method, Change. Because the parameter is a reference to myArray, it is possible to change the values of the array elements. However, the attempt to reassign the parameter to a different memory location only works inside the method and does not affect the original variable, myArray.

// PassingParams4.cs // Passing an array to a method without the ref keyword.// Compare the results to those of Example 5.using System;class PassingRefByVal { static void Change(int[] arr) { arr[0]=888; // This change affects the original element. arr = new int[5] {-3, -1, -2, -3, -4}; // This change is local.Console.WriteLine(“Insidethemethod,thefirstelementis:{0}”,arr[0]); }

Page 64: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

53

public static void Main() { int[] myArray = {1,4,5};Console.WriteLine(“InsideMain,beforecallingthemethod,thefirstelementis:{0}”,myArray[0]); Change(myArray);Console.WriteLine(“InsideMain,aftercallingthemethod,thefirstelementis:{0}”,myArray[0]); }}

OutputInsideMain,beforecallingthemethod,thefirstelementis:1Insidethemethod,thefirstelementis:-3InsideMain,aftercallingthemethod,thefirstelementis:888

Code detailsThe array, myArray, which is a reference type, is passed to the method without the ref parameter. •In this case, a copy of the reference, which points to myArray, is passed to the method. •The output shows that it is possible for the method to change the contents of an array element (from 1 to •888). Allocating a new portion of memory by using the new operator inside the Change method makes the variable •arr reference a new array. Any changes after that will not affect the original array, myArray, which is created inside Main. •Two arrays are created in this example, one inside Main and one inside the Change method.•

4.7.11 Passing Reference Types by ReferenceThis example is the same as Passing Reference Types by Value except for using the ref keyword in the method header and call. Any changes that take place in the method will affect the original variables in the calling program.

// PassingParams5.cs // Passing an array to a method with the ref keyword.// Compare the results to those of Example 4.using System;class PassingRefByRef { static void Change(ref int[] arr) { // Both of the following changes will affect the original variables: arr[0]=888; arr = new int[5] {-3, -1, -2, -3, -4};Console.WriteLine(“Insidethemethod,thefirstelementis:{0}”,arr[0]); } public static void Main() { int[] myArray = {1,4,5};Console.WriteLine(“InsideMain,beforecallingthemethod,thefirstelementis:{0}”,myArray[0]); Change(ref myArray);Console.WriteLine(“InsideMain,aftercallingthemethod,thefirstelementis:{0}”,myArray[0]); }}

Page 65: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

54

Dot Net Framework (Using C#)

OutputInsideMain,beforecallingthemethod,thefirstelementis:1Insidethemethod,thefirstelementis:-3InsideMain,aftercallingthemethod,thefirstelementis:-3

Code detailsAll of the changes that take place inside the method affect the original array in Main.•The original array is reallocated using the new operator. •AftercallingtheChangemethod,anyreferencetomyArraypointstothefive-elementarray,whichiscreated•in the Change method.

4.8 Swapping Two StringsSwapping strings is a good example of passing reference-type parameters by reference. In the example given below, twostrings,str1andstr2,areinitialisedinMainandpassedtotheSwapStringsmethodasparametersmodifiedbythe ref keyword. The two strings are swapped inside the method and inside Main as well.

// PassingParams6.csusing System;class SwappinStrings{ static void SwapStrings(ref string s1, ref string s2) // The string parameter x is passed by reference. // Any changes on parameters will affect the original variables. { string temp = s1; s1 = s2; s2 = temp;Console.WriteLine(“Insidethemethod:{0},{1}”,s1,s2); } public static void Main() {stringstr1=“John”;stringstr2=“Smith”;Console.WriteLine(“InsideMain,beforeswapping:{0}{1}”, str1, str2); SwapStrings(ref str1, ref str2); // Passing strings by referenceConsole.WriteLine(“InsideMain,afterswapping:{0},{1}”, str1, str2); }}

OutputInside Main, before swapping: John SmithInside the method: Smith, JohnInside Main, after swapping: Smith, JohnCode details

The parameters need to be passed by reference to affect the variables in the calling program. •If we remove the ref keyword from both the method header and the method call, no changes will take place in •the calling program.

4.8.1 Pass By Value

Page 66: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

55

While passing parameters of value type only the local copy of the variable is passed, so if the copy is changed it will not affect the original variable.

For example:void Set (int i)

{i=10;}

static void main ( ){

MyApp m = new MyApp ( ); int x = 0; // value type m.Set (x); // pass value of x System.Console.Write(x); //0

}

4.8.2 Pass By ReferenceFor reference data types C# uses true pass by reference. This means that when a reference type is passed it is not only possible to change its state, but also to replace entire object and have the change propagate back to the original object.

For examplevoid Set (int [] i) (i = new int []){ 10};static void main ( ){ MyApp m = new MyApp ( ); Int[] y = {0}; // reference type m.Set (y); // pass object reference System.Console.Write(y[0]); // 10}

4.9 In and Out ParametersC# actually supports three different types of pass-by-reference: ref, in , and out. In and out are special cases of the ref keyword.

Aninparameterisaparameterthatispassedbyreferenceintoamethod.Specifically,theactualparametermustalready have a value and that value is assigned to the formal parameter of the method. It is not possible to assign a new value to an in parameter in the body of the method.

Anoutparameterisaparameterthatispassedbyreferenceoutfromamethod.Specifically,theformalparametermust be assigned a value by the method before the method is called, and that value is then returned to the actual parameter of the calling method. It is not possible to use the value of an out parameter in the method body until a value has been assigned to that parameter.

Page 67: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

56

Dot Net Framework (Using C#)

Output parametersOutput parameters are used to pass data from inside the method back out to the calling code. They are very similar toreferenceparameters.Likereferenceparameters,outputparametersalsohavethefollowingrequirements:

Amodifiershouldbeused inboth themethoddeclarationand the invocation.Withoutputparameters, the•modifierisout,ratherthanref.The actual parameter must be a variable. It cannot be another type of expression.•

For example, the following code declares a method called MyMethod, which takes a single output parameter.

outmodifier↓void MyMethod( out int val ) // Method declaration{ ... }...int y = 1; // Variable for the actual parameterMyMethod ( out y ); // Method call ↑outmodifier

Like reference parameters, the formal parameters of output parameters act as aliases for the actual parameters. Both the formal parameter and the actual parameter are names for the same memory location. Clearly, any changes made to a formal parameter inside the method will be visible through the actual parameter variable after the method.

Unlikereferenceparameters,outputparametersrequirethefollowingInside the method, an output parameter must be assigned to before it can be read from. This means that the •initial values of the parameters are irrelevant, and that you don’t have to assign values to the actual parameters before the method call.Every output parameter must be assigned to, before the method exits.•

4.10 Variable Arguments ListWhenever a function member is invoked it is associated with an argument list. This argument list provides actual values or variable references for the parameters of the function member. The type of function member decides the syntax for specifying the argument list of a function member.

Forexample,constructors,methods,anddelegates,theargumentsarespecifiedasanargument-list,asdescribed•below.

argument-list:argumentargument-list , argument

argument:expressionref variable-referenceout variable-reference

The argument list is empty while invoking the get accessor, and while invoking the set accessor it consists of •theexpressionspecifiedastherightoperandoftheassignmentoperatorforproperties.Forevents,theargumentlistconsistsoftheexpressionspecifiedastherightoperandofthe+=or-=operator.•Forindexers,theargumentlistconsistsoftheexpressionsspecifiedbetweenthesquarebracketsintheindexer•access.

Page 68: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

57

Wheninvokingthesetaccessor,theargumentlistadditionallyincludestheexpressionspecifiedastheright•operand of the assignment operator.Foruser-definedoperators,theargumentlistconsistsofthesingleoperandoftheunaryoperatororthetwo•operands of the binary operator.

Note:Theargumentsofproperties,events,indexers,anduser-definedoperatorarealwayspassedasvalueparameters.Reference and output parameters are not supported for these categories of function members.

An argument-list consists of one or more arguments, separated by commas. Each argument can take one of the following forms:

An expression, indicating that the argument is passed as a value parameter.•The keyword ref followed by a variable-reference, indicating that the argument is passed as a reference •parameter. Avariablemustbedefinitelyassignedbeforeitcanbepassedasareferenceparameter.•Avolatilefieldcannotbepassedasareferenceparameter.•The keyword out followed by a variable-reference, indicating that the argument is passed as an output •parameter. Avariableisconsidereddefinitelyassignedfollowingafunctionmemberinvocationinwhichthevariableis•passed as an output parameter. Avolatilefieldcannotbepassedasanoutputparameter.•

4.11 Runtime Evaluation of Argument ListDuring the run-time processing of a function member invocation, the expressions or variable references of an argument list are evaluated in order, from left to right, as follows:

For a value parameter, the argument expression is evaluated and an implicit conversion to the corresponding •parameter type is performed. The resulting value becomes the initial value of the value parameter in the function member invocation.•For a reference or output parameter, the variable reference is evaluated and the resulting storage location becomes •the storage location represented by the parameter in the function member invocation. If the variable reference given as a reference or output parameter is an array element of a reference-type, a run-•time check is performed to ensure that the element type of the array is identical to the type of the parameter. If this check fails, a System.ArrayTypeMismatchException is thrown.•Methods, indexers, and instance constructors may declare their right-most parameter to be a parameter array. •Such function members are invoked either in their normal form or in their expanded form depending on which is applicable.

When a function member with a parameter array is invoked in its normal form, the argument given for the parameter array must be a single expression of a type that is implicitly convertible to the parameter array type. In this case, the parameter array acts precisely like a value parameter.

When a function member with a parameter array is invoked in its expanded form, the invocation must specify zero or more arguments for the parameter array, where each argument is an expression of a type that is implicitly convertible to the element type of the parameter array. In this case, the invocation creates an instance of the parameter array type with a length corresponding to the number of arguments, initialises the elements of the array instance with the given argument values, and uses the newly created array instance as the actual argument.

Page 69: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

58

Dot Net Framework (Using C#)

The expressions of an argument list are always evaluated in the order they are written. For example,

class Test{ static void F(int x, int y, int z) {System.Console.WriteLine(“x={0},y={1},z={2}”,x,y,z); } static void Main() { int i = 0; F(i++, i++, i++); }}

Output:

x = 0, y = 1, z = 2

The array co-variance rules permit a value of an array type A[ ] to be a reference to an instance of an array type B[ ], provided an implicit reference conversion exists from B to A. Because of these rules, when an array element of areference-typeispassedasareferenceoroutputparameter,arun-timecheckisrequiredtoensurethattheactualelement type of the array is identical to that of the parameter. For example,

class Test{ static void F(ref object x) {...} static void Main() { object[] a = new object[10]; object[] b = new string[10]; F(ref a[0]); // Ok F(ref b[1]); ` // ArrayTypeMismatchException }}

In the above program the second invocation of F causes a System.ArrayTypeMismatchException to be thrown because the actual element type of b is string and not object.

When a function member with a parameter array is invoked in its expanded form, the invocation is processed exactly as if an array creation expression with an array initialiser was inserted around the expanded parameters. For example,

void F(int x, int y, params object[] args);

The above program gives following invocations of the expanded form of the method

F(10, 20);F(10, 20, 30, 40);F(10,20,1,“hello”,3.0);correspond exactly to

F(10, 20, new object[] {});F(10, 20, new object[] {30, 40});F(10,20,newobject[]{1,“hello”,3.0});

Page 70: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

59

In particular, note that an empty array is created when there are zero arguments given for the parameter array.

4.12 Method OverloadingA class can have more than one method with the same name. This is called method overloading. Each method with the same name must have a different signature than the others.

The signature of a method consists of the following information from the method header of the method •declaration:The name of the method.• The number of parameters.• The data types and order of the parameters.•Theparametermodifiers.• The return type is not part of the signature—although it is a common mistake to believe that it is.•The names of the formal parameters are also not part of the signature.•

ExampleNot part of signature↓long AddValues( int a, out int b) { ... }↑Signature

For example, the following four methods are overloads of the method name AddValues:

class A{long AddValues( int a, int b) { return a + b; }long AddValues( int a, int b, int c) { return a + b + c; }longAddValues(floata,floatb){returna+b;}long AddValues( long a, long b) { return a + b; }}

The following code shows an illegal attempt at overloading the method name AddValues.

The two methods differ only on the return types and the names of the formal parameters. But they still have the same signature, because they have the same method name; and the number, types, and order of their parameters are the same. The compiler would produce an error message for this code.

class B Signature{↓long AddValues( long a, long b) { return a+b; }int AddValues( long c, long d) { return c+d; }}↑ Signature

4.13 ArraysProbably the most common way to aggregate data is to use an array. In C# an array is an object that contains a collectionofobjects,allofthesametype.Anarrayrepresentsafixednumberofelementsofaparticulartype.Anarrayisdenotedwithsquarebracketsaftertheelementtype.Thefollowingexampledeclaresanarrayof5characters:

char[] vowels = new char[5];

Page 71: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

60

Dot Net Framework (Using C#)

Squarebracketsalsoindexthearray,accessingaparticularelementbyposition:

Theelementsinanarrayarealwaysstoredinacontiguousblockofmemory,providinghighlyefficientaccess.Forexample,

int[] a = new int[5];

Aboveexampleallocatesanarrayoffiveintegersandassignsittothevariablea.Theelementsofanarrayareaccessedusinginteger-valuedindices.InC#thefirstelementofanarrayalwayshasindexzero.Thus,thefiveelementsofarrayaarea[0],a[1],...,a[4].AllarrayobjectsinC#haveanintpropertycalledLength,thevalueofwhichisequaltothenumberofarrayelements.Inthiscase,aLengthhasthevalue5.

C# checks at run-time that the index used in every array access is valid. Valid indices fall between zero and one. If an invalid index expression is used, an IndexOutOfRangeException exception is thrown.

It is important to understand that in C#, the variable a refers to an array object of type int[].

int[] b;b = a;

Inparticular,thesequenceofstatementsasabovecausesthevariablebtorefertothesamearrayobjectasvariablea.Onceallocated,thesizeofaC#arrayobjectisfixed.Thatis,itisnotpossibletoincreaseordecreasethesizeofagiven array. Of course, it is always possible to allocate a new array of the desired size, but it is up to the programmer to copy the values from the old array to the new one.

4.13.1 1-D arrayWecandeclareanarrayoffiveintegersasinthefollowingexample:

int[] array = new int[5];

This array contains the elements from array [0] to array[4]. The new operator is used to create the array and initialise the array elements to their default values. In this example, all the array elements are initialised to zero. An array that stores string elements can be declared in the same way. For example:

string[] stringArray = new string[6];

Array initialisationItispossibletoinitialiseanarrayupondeclaration,inwhichcase,therankspecifierisnotneededbecauseitisalready supplied by the number of elements in the initialisation list. For example:

int[] array1 = new int[5] { 1, 3, 5, 7, 9 };

A string array can be initialised in the same way. The following is a declaration of a string array where each array element is initialised by a name of a day:string[]weekDays=newstring[]{“Sun”,“Mon”,“Tue”,“Wed”,“Thu”,“Fri”,“Sat”};

When we initialise an array upon declaration, it is possible to use the following shortcuts:

int[] array2 = { 1, 3, 5, 7, 9 };string[]weekDays2={“Sun”,“Mon”,“Tue”,“Wed”,“Thu”,“Fri”,“Sat”};

It is possible to declare an array variable without initialisation, but we must use the new operator when we assign an array to this variable. For example:

Page 72: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

61

int[] array3;array3 = new int[] { 1, 3, 5, 7, 9 }; // OK//array3 = {1, 3, 5, 7, 9}; // Error

4.13.2 Value Type and Reference Type ArraysValue type and reference type arrays can be explained with the help of following example, consider the following array declaration:

SomeType[] array4 = new SomeType[10];

The result of this statement depends on whether SomeType is a value type or a reference type. If it is a value type, the statement results in creating an array of 10 instances of the type SomeType. If SomeType is a reference type, the statement creates an array of 10 elements, each of which is initialised to a null reference.

4.13.3 Declaring 1-D arraySingle-dimensional arrays are declared as follows:

int[] numbers = new int[5];

4.13.4 2-D arrayArrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns:

int[,] array = new int[4, 2];

Also, the following declaration creates an array of three dimensions, 4, 2, and 3:

int[, ,] array1 = new int[4, 2, 3];

4.13.5 Array initialisationWe can initialise the array upon declaration as shown in the following example:

int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };int[, ,] array3D = new int[,,] { { { 1, 2, 3 } }, { { 4, 5, 6 } } };

We can also initialise the array without specifying the rank as follows:

int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };If we choose to declare an array variable without initialisation, we must use the new operator to assign an array to the variable. For example:

int[,] array5;array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // OK//array5 = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error

We can also assign a value to an array element, for example:

array5[2, 1] = 25;

The following code example initialises the array variables to default (except for jagged arrays):

int[,] array6 = new int[10, 10];

Page 73: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

62

Dot Net Framework (Using C#)

4.13.6 Declaring Multi-dia ArrayMultidimensional arrays are declared as follows:

string [,] names = new string[5,4];

4.13.7 Array-of-arrays (jagged)Jagged arrays are declared as foolows:

byte[ ][ ] scores = new byte[5][ ];for (int x = 0; x < scores.Length; x++) { scores[x] = new byte[4];}

4.14 Programming Arrays in C#Various programming have become easier using arrays. Arrays are probably one of the most important topics in C#.InC#,anarrayindexstartsatzero.Thatmeansthefirstitemofanarraystartsatthe0thposition.Thepositionof the last item on an array will total number of items - 1. So if an array has 10 items, the last 10th item is at 9th position. InC#,arrayscanbedeclaredasfixed lengthordynamic.Afixed lengtharraycanstoreapredefinednumberofitems.Adynamicarraydoesnothaveapredefinedsize.Thesizeofadynamicarrayincreasesasweaddnewitemstothearray.Wecandeclareanarrayoffixedlengthordynamic.Wecanevenchangeadynamicarraytostaticafteritisdefined.

Thefollowingcodesnippetdefinesthesimplestdynamicarrayofintegertypesthatdoesnothaveafixedsize.

int [] intArray;

Intheabovecode,thedeclarationofanarraystartswithatypeofarrayfollowedbyasquarebracket([])andnameof the array.

The following code declares an array that can store 5 items only starting from index 0 to 4.

int[] intArray;intArray = new int[5];

The following code declares an array that can store 100 items starting from index 0 to 99.

int[] intArray;intArray = new int[100];

4.15 Defining Arrays of Different TypesWecandefinearraysofanytypesuchasdouble,character,andstring.InC#,arraysareobjects.Thatmeansthatdeclaring an array doesn’t create an array. After declaring an array, we need to instantiate an array by using the “new”operator.Thefollowingcodedefinesarraysofdouble,char,bool,andstringdatatypes.

double[] doubleArray = new double[5];char[] charArray = new char[5];bool[] boolArray = new bool[2];string[] stringArray = new string[10];

Page 74: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

63

4.15.1 Initialising ArraysOnce an array is declared, the next step is to initialise an array. The initialisation process of an array includes adding actual data to the array. The following code creates an array of 3 items and values of these items are added when the array is initialised.

//Initialiseafixedarrayint[] staticIntArray = new int[3] {1, 3, 5}; Alternative, we can also add array items one at a time as listed in the following code. //Initialiseafixedarrayoneitematatimeint[ ] staticIntArray = new int[3];staticIntArray[0] = 1;staticIntArray[1] = 3;staticIntArray[2] = 5; The following code declares a dynamic array with string values. // Initialise a dynamic array items during declarationstring[] strArray=newstring[] { “MaheshChand”, “MikeGold”, “RajBeniwal”, “PraveenKumar”, “DineshBeniwal”};

4.15.2 Accessing ArraysWe can access an array item by passing the item index in the array. The following code creates an array of three items and displays those items on the console.

//Initialiseafixedarrayoneitematatimeint[ ] staticIntArray = new int[3];staticIntArray[0] = 1;staticIntArray[1] = 3;staticIntArray[2] = 5; // Read array items one by oneConsole.WriteLine(staticIntArray[0]);Console.WriteLine(staticIntArray[1]);Console.WriteLine(staticIntArray[2]); This method is useful when we know what item we want to access from an array. If we try to pass an item index greater than the items in array, we will get an error.

Accessing an Array using a foreach LoopThe foreach control statement (loop) is used to iterate through the items of an array. For example, the following code uses foreach loop to read all items of an array of strings. // Initialise a dynamic array items during declarationstring[] strArray=newstring[] { “MaheshChand”, “MikeGold”, “RajBeniwal”, “PraveenKumar”, “DineshBeniwal”}; // Read array items using foreach loopforeach (string str in strArray){ Console.WriteLine(str);}

Page 75: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

64

Dot Net Framework (Using C#)

This approach is used when we do not know the exact index of an item in an array and needs to loop through all the items.

4.15.3 Array TypesArrays can be divided into the following four categories.

Single-dimensional arrays•Multidimensional arrays or rectangular arrays•Jagged arrays•Mixed arrays.•

4.15.4 Single Dimension ArraysSingle-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items ofapredefinedtype.Allitemsinasingledimensionarrayarestoredcontiguouslystartingfrom0tothesizeofthearray-1.Thefollowingcodedeclaresanintegerarraythatcanstore3items.Aswecanseefromthecode,firstwedeclare the array using [ ] bracket and after that we instantiate the array by calling the new operator.

int[] intArray;intArray = new int[3];

Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not initialised, its items are automatically initialised to the default initial value for the array type if the array is not initialised at the time it is declared.

The following code declares and initialises an array of three items of integer type.

int[] staticIntArray = new int[3] {1, 3, 5};

The following code declares and initialises an array of 5 string items.

string[]strArray=newstring[5]{“Mahesh”,“Mike”,“Raj”,“Praveen”,“Dinesh”}; We can even directly assign these values without using the new operator.

string[]strArray={“Mahesh”,“Mike”,“Raj”,“Praveen”,“Dinesh”};

We can initialize a dynamic length array as follows:

string[]strArray=newstring[]{“Mahesh”,“Mike”,“Raj”,“Praveen”,“Dinesh”}; 4.15.5 Multi-Dimensional ArraysA multi-dimensional array, also known as a rectangular array is an array with more than one dimension. The form of a multi-dimensional array is a matrix.

Declaring a multi-dimensional arrayAmulti-dimensionalarraycanbefixed-sizedordynamicsized.Amultidimensionarrayisdeclaredas following:

Page 76: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

65

string[,] mutliDimStringArray;

Initialising multi-dimensional arraysThefollowingcodeisanexampleoffixed-sizedmulti-dimensionalarraysthatdefinestwomultidimensionarrayswithamatrixof3x2and2x2.Thefirstarraycanstore6itemsandsecondarraycanstore4items.Bothofthesearrays are initialised during the declaration.

int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };string[,]names=newstring[2,2]{{“Rosy”,“Amy”},{“Peter”,“Albert”}};

Examplesofmulti-dimensionaldynamicarraysaregivenbelow.Herenumberofitemsofthearrayarenotfixed.The following code creates two multi-dimensional arrays with no limit.

int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };string[,]names=newstring[,]{{“Rosy”,“Amy”},{“Peter”,“Albert”}};

We can also omit the new operator as we did in single dimension arrays. We can assign these values directly without using the new operator. For example:

int[,] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } };string[,]names={{“Rosy”,“Amy”},{“Peter”,“Albert”}}; We can also initialize the array items one item at a time. The following code is an example of initialising array items one at a time. int[,] numbers = new int[3, 2];numbers[0, 0] = 1;numbers[1, 0] = 2;numbers[2, 0] = 3;numbers[0, 1] = 4;numbers[1, 1] = 5;numbers[2, 1] = 6;

Accessing multi-dimensional arraysA multi-dimensional array items are represented in a matrix format and to access it’s items, we need to specify the matrix dimension. For example, item (1,2) represents an array item in the matrix at second row and third column. Thefollowingcodedescribeshowtoaccessnumbersarraydefinedintheabovecode.

Console.WriteLine(numbers[0,0]);Console.WriteLine(numbers[0, 1]);Console.WriteLine(numbers[1, 0]);Console.WriteLine(numbers[1, 1]);Console.WriteLine(numbers[2, 0]);Console.WriteLine(numbers[2, 2]);

Page 77: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

66

Dot Net Framework (Using C#)

4.15.6 Jagged ArraysA jagged array is an array whose elements are arrays. The elements of a jagged array are other arrays. The elements ofajaggedarraycanbeofdifferentdimensionsandsizes.Ajaggedarrayissometimescalledan“arrayofarrays.”The following examples show how to declare, initialise, and access jagged arrays. Declaring jagged arraysDeclaration of a jagged array involves two brackets. For example, the following code declares a jagged array that has three items of an array. int[][] intJaggedArray = new int[3][]; The following code declares a jagged array that has two items of an array. string[][] stringJaggedArray = new string[2][]; Initialising jagged arraysBefore a jagged array can be used, its items must be initialised. The following code snippet initialises a jagged array;thefirstitemwithanarrayofintegersthathastwointegers,seconditemwithanarrayofintegersthathas4integers, and a third item with an array of integers that has 6 integers.

// Initialising jagged arraysintJaggedArray[0] = new int[2];intJaggedArray[1] = new int[4];intJaggedArray[2] = new int[6];

We can also initialise a jagged array’s items by providing the values of the array’s items. The following code initialises item an array’s items directly during the declaration. // Initialising jagged arraysintJaggedArray[0] = new int[2]{2, 12};intJaggedArray[1] = new int[4]{4, 14, 24, 34};intJaggedArray[2] = new int[6] {6, 16, 26, 36, 46, 56 }; Accessing jagged arraysWe can access a jagged array’s items individually in the following way:Console.Write(intJaggedArray3[0][0]);Console.WriteLine(intJaggedArray3[2][5]); We can also loop through all of the items of a jagged array. The Length property of an array helps a lot; it gives us the number of items in an array. The following code loops through all of the items of a jagged array and displays them on the screen. // Loop through all itesm of a jagged arrayfor (int i = 0; i < intJaggedArray3.Length; i++){System.Console.Write(“Element({0}):“,i); for (int j = 0; j < intJaggedArray3[i].Length; j++) {System.Console.Write(“{0}{1}”,intJaggedArray3[i][j],j==(intJaggedArray3[i].Length-1)?“”:““); } System.Console.WriteLine();}

Page 78: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

67

4.15.7 Mixed ArraysMixed arrays are a combination of multi-dimension arrays and jagged arrays. Consider the examples given below to understand the mixed arrays. Create a console application using Visual Studio 2010 or Visual C# Express and copy and paste this code. Console.WriteLine(“SingleDimensionArraySample”);// Single dim arraystring[] strArray=newstring[] { “MaheshChand”, “MikeGold”, “RajBeniwal”, “PraveenKumar”, “DineshBeniwal”};// Read array items using foreach loopforeach (string str in strArray){ Console.WriteLine(str);}Console.WriteLine(“-----------------------------”); Console.WriteLine(“Multi-DimensionArraySample”);string[,]string2DArray=newstring[2,2]{{“Rosy”,“Amy”},{“Peter”,“Albert”}};foreach (string str in string2DArray){ Console.WriteLine(str);}Console.WriteLine(“-----------------------------”); Console.WriteLine(“JaggedArraySample”);int[][] intJaggedArray3 ={ new int[] {2,12}, new int[] {14, 14, 24, 34}, new int[] {6, 16, 26, 36, 46, 56}};// Loop through all itesm of a jagged arrayfor (int i = 0; i < intJaggedArray3.Length; i++){Console.Write(“Element({0}):“,i); for (int j = 0; j < intJaggedArray3[i].Length; j++) {Console.Write(“{0}{1}”,intJaggedArray3[i][j],j==(intJaggedArray3[i].Length-1)?“”:““); } Console.WriteLine();}Console.WriteLine(“-----------------------------”);Listing 1

Page 79: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

68

Dot Net Framework (Using C#)

Theoutputsofthecodewrittenwilllooklikethefiguregiven.

Xfile://C:/Book/C#/ArrayInCSharpSample/ArrayInCSharpSample/bin/Debug/ArrayInCSharpSample

Singal Dimension Array SampleMahesh ChandMike GoldRaj BeniwalPraveen KumarDinesh Kumar

Multy Dimension Array SampleRosyAmyPeterAlbart

Jagged Array SampleElement (0) : 2 12Element (1) : 14 14 24 34Element (2) : 6 16 26 36 46 56

Fig. 4.1 Output of mixed array

4.16 Array ClassArray class is the mother of all arrays and provides functionality for creating, manipulating, searching, and sorting arraysin.NETFramework.Arrayclass,definedintheSystemnamespace,isthebaseclassforarraysinC#.Arrayclass is an abstract base class that means we cannot create an instance of the Array class. Creating an array classArrayclassprovidestheCreateInstancemethodtoconstructanarray.TheCreateInstancemethodtakesfirstparameteras the type of items and second and third parameters are the dimension and their range. Once an array is created, we use SetValue method to add items to an array. The following code creates an array and adds three items to the array. As we can see the type of the array items is string and range is 3. We will get an error message if we try to add 4th item to the array. Array stringArray = Array.CreateInstance(typeof(String), 3);stringArray.SetValue(“MaheshChand”,0);stringArray.SetValue(“RajKumar”,1);stringArray.SetValue(“NeelBeniwal”,2); Note: Calling SetValue on an existing item of an array overrides the previous item value with the new value.

Page 80: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

69

Following code creates a multi-dimensional array. Array intArray3D = Array.CreateInstance(typeof(Int32), 2, 3, 4);for (int i = intArray3D.GetLowerBound(0); i <= intArray3D.GetUpperBound(0); i++) for (int j = intArray3D.GetLowerBound(1); j <= intArray3D.GetUpperBound(1); j++) for (int k = intArray3D.GetLowerBound(2); k <= intArray3D.GetUpperBound(2); k++) { intArray3D.SetValue((i * 100) + (j * 10) + k, i, j, k); } foreach (int ival in intArray3D){ Console.WriteLine(ival);}

4.17 Array PropertiesArrayshavefivespecificproperties,explainbelow:

IsFixedSize-Returnavalueindicatingifanarrayhasafixedsizeornot.•IsReadOnly- Returns a value indicating if an array is read-only or not.•LongLength- Returns a 64-bit integer that represents total number of items in all the dimensions of an array.•Length- Returns a 32-bit integer that represents the total number of items in all the dimensions of an array.•Rank- Returns the number of dimensions of an array.•

Following code creates an array and uses array properties to display property values. int[] intArray = new int[3] {0, 1, 2};if(intArray.IsFixedSize){Console.WriteLine(“Arrayisfixedsize”);Console.WriteLine(“Size:”+intArray.Length.ToString());Console.WriteLine(“Rank:”+intArray.Rank.ToString());}

Theoutputofcodeabovewilllooklikefollowingfigure:

Array is fixed sizeSize :Rank :

Xfile://C:/Book/C#/ArrayINCSharpSample/ArrayIn

Fig. 4.2 Output of the code

Page 81: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

70

Dot Net Framework (Using C#)

SummaryA method is a block of code containing a series of statements.•Methods are declared within a class or struct by specifying the access level, the return value, the name of the •method, and any method parameters.Every C# application must contain a single Main method specifying where program execution is to begin.•The main method is declared inside a class or struct. It must be static and it should not be public.•When a C# method is called by another method of the same class is known as nesting of methods.•Aparameterdeclaredwithnomodifiersisavalueparameter.•Aparameterdeclaredwitharefmodifierisareferenceparameter.•Aparameterdeclaredwithanoutmodifierisanoutputparameter.•Aparameterdeclaredwithaparamsmodifierisaparameterarray.•Parameters can be passed either by value or by reference.•Any changes to the parameter that take place inside the method have no affect on the original data stored in •the variable.A variable of a reference type does not contain its data directly; it contains a reference to its data.•An array is an object that contains a collection of objects, all of the same type.•Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of •itemsofapredefinedtype.A jagged array is an array whose elements are arrays. The elements of a jagged array are other arrays.•Before a jagged array can be used, its items must be initialised.•Array class is the mother of all arrays and provides functionality for creating, manipulating, searching, and •sorting arrays in .NET Framework.

ReferencesHejlsberg, A., Torgersen, M., Wiltamuth, S. and Golde. P., 2010. • The C# Programming Language, 4th ed., Pearson Education Publication.Jack Xu, 2008. • Practical Numeric Methods with C#, C# Math Application SeriesChand, M., 2002, • Working With Arrays in C# .NET [Online], Available at: <http://www.scriptcanal.com/articles_73_Working-with-Arrays-in-C%23--NET.html> [Accessed 31 January 2012].Robert, J., 2006, • Introduction to C#, [Online] Available at: <http://zone.ni.com/devzone/cda/ph/p/id/44#toc0> [Accessed 31 January 2012].ecturesnippets, 2011. Visual • C# 2010 - Methods Part 1 (Creating a Simple Method), [Video Online] Available at: <http://www.youtube.com/watch?v=rlv7Er3I9oU> [Accessed 3 February 2012].csharpdemos, 2011. • C# Tutorial 10 - Methods and Return Types, [Video Online] Available at: <http://www.youtube.com/watch?v=9Y1giYg-Zt8> [Accessed 3 February 2012].

Recommended ReadingHarvey, M. D. and Paul, J. D., 2006. • C# for Programmers, Pearson Education.Michelsen, K., 2002. • C# Primer Plus, Sams Publication.Blum, R., 2003, • C# Network Programming, SYBEX san Francisco London.

Page 82: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

71

Self Assessment

Calling a method on an object is similar to accessing a ___________.1. fielda. classb. object namec. argumentsd.

Which one of the following is a property of an array?2. IsFixedSizea. OnFixedSizeb. IsRankc. IsLengthd.

The original array can be reallocated using the ________ operator. 3. arraya. newb. oldc. refd.

While passing parameters of value type only the local copy of the ________ is passed.4. variablea. literalb. constantc. data typed.

In and out are special cases of the _______keyword.5. in a. outb. IOc. refd.

Mixed arrays are a combination of 6. 1-D array and 2-D arraya. multi-dimension arrays and jagged arraysb. 1-D array and jagged arrayc. 2-D array and multi-dimension arrayd.

7. Which of the following statements is true?7. Rectangular array is a type of array. a. We cannot access a jagged arrays item.b. Data is used to aggregate arrays.c. Single dimensional arrays are very complicated.d.

Page 83: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

72

Dot Net Framework (Using C#)

Using the following declaration:8. int [ ] x = {12, 13, 14, 15, 16, 17, 18, 19};

What does x [8] refer to?

19a. 18b. ‘\0’c. 0d.

An array is a list of data items that ___________ .9. all have the same typea. all have different namesb. all are integersc. allareoriginallysettonull(‘\0’)d.

Thevaluecontainedwithinthesquarebracketsthatisusedtoindicatethelengthofthearraymustbea(n):10. classa. doubleb. stringc. integerd.

Page 84: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

73

Chapter V

Classes and Objects

Aim

The aim of this chapter is to:

introduce the concept of objects and classes•

elucidate class declaration and access•

explain how to access the class member to increase program performance•

Objectives

The objectives of this chapter are to:

explain the types of constructors•

describe member class access•

elucidate member initialisation•

Learning outcome

At the end of this chapter, you will be able to:

declare a class and class member in the program•

identify and use constructors•

understand C# constants and read only properties•

Page 85: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

74

Dot Net Framework (Using C#)

5.1 IntroductionA class is a construct that enables to create our own custom types by grouping together variables of other types, methodsandevents.Aclassislikeablueprint.Itdefinesthedataandbehaviorofatype.Iftheclassisnotdeclaredas static, client code it can be used by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable. A class is the most common kind of reference type. Classes are declared using the keyword class. It takes the following form:

[attributes][modifiers]classidentifier[:base-list]{class-body}[;]where: attributes (Optionalmodifiers(Optional)Theallowedmodifiersarenew,abstract,sealed,andthefouraccessmodifiers.identifierThe class name.base-list (Optional)

A list that contains the one base class and any implemented interfaces, all separated by commas.

5.2 Overview of ClassesC#providessixuser-definedtypes.Themostimportantofthese,istheclass.Aclassisanactivedatastructure.Beforethedaysofobject-orientedanalysisanddesign,programmersthoughtofaprogramadjustasequenceofinstructions. The focus at that time was on structuring and optimising those instructions. With the advent of the object-oriented paradigm, the focus changed from optimising instructions to organising a program’s data and functions into encapsulated sets of logically related data items and functions, called classes. A class is a data structure that can store data and execute code. It contains the following:

Data members, store data associated with the class or an instance of the class.•Data members generally model the attributes of the real-world object the class represents.•Function members, execute code. Function members generally model the functions and actions of the real-world •object the class represents.A C# class can have any number of data and function members. The members can be any combination of nine •possible member types.

Note Classes are encapsulated sets of logically related data items and functions that generally represent objects in the real world or a conceptual world.

5.3 Programs and Classes: A Quick ExampleA running C# program is a group of interacting type objects, most of which are instances of classes. For example, suppose you have a program simulating a poker game. When it is running, it has an instance of a class called Dealer, whose job it is to run the game, and several instances of a class called Player, which represent the players of the game.

The Dealer object stores such information as the current state of the card deck and the number of players. Its actions includeshufflingthedeckanddealingthecards.ThePlayerclassisverydifferent.Itstoressuchinformationasthe player’s name and the amount of money left to bet, and performs such actions as analyzing the player’s current hand and placing bets.

Page 86: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

75

Dealer

theDealer

Player

Player

Player

player1

player3

player2

Running Poker Program

Fig. 5.1 The objects in a running program

A real program would undoubtedly contain dozens of other classes besides Dealer and Player. These would include classes such as Card and Deck. Each class models some thing that is a component of the poker game.

5.3.1 Declaring a ClassAlthoughtypesint,double,andchararedefinedbyC#,classessuchasDealerandPlayer,aswecanprobablyguess,arenotdefinedbythelanguage.Ifwewanttousetheclassinaprogram,wewillhavetodefinethemourself.Wecan do this by writing a class declaration.

Aclassdeclarationdefinesthecharacteristicsandmembersofanewclass.Itdoesnotcreateaninstanceoftheclass,but creates the template from which class instances will be created. The class declaration provides the following:

The class name•The members of the class•The characteristics of the class•

The following is an example of the minimum syntax for a class declaration. The curly braces contain the member declarations that make up the class body. Class members can be declared in any order inside the class body. This meansthatitisperfectlyfineforthedeclarationofamembertorefertoanothermemberthatisnotyetdefineduntilfurther down in the class declaration.

Page 87: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

76

Dot Net Framework (Using C#)

Keyword Class Name↓ ↓Class MyFirstClass{ MemberDeclarations}For example, the following code shows the outlines of two class declarations:Class Dealer // Class Declaration{...}Class Player // Class Declaration{...}Note:Sinceaclassdeclaration“defines”anewclass,youwilloftenseeaclassdeclarationreferredtoasa“classdefinition”bothintheliteratureandincommonusageamongprogrammers.

5.3.2 Class MembersFields and methods are the most important of the class member types. Fields are data members and methods are function members.

5.3.3 Fields

Afieldisavariablethatbelongstoaclass.•Itcanbeofanytype,eitherpredefinedoruser-defined.•Likeallvariables,fieldsstoredata,andhavethefollowingcharacteristics:•

They can be written to. �They can be read from. �

Theminimumsyntaxfordeclaringafieldisthefollowing:Type↓TypeIdentifier; ↑ Field name Forexample,thefollowingclasscontainsthedeclarationoffieldMyField,whichcanstoreanintvalue:Class MyClass{Type↓IntMyfield; Field name}

5.3.4 Explicit and Implicit Field InitialisationSinceafieldisakindofvariable,thesyntaxforafieldinitialiseristhesameasthatofthevariable

Afieldinitialiserispartofthefielddeclaration,andconsistsofanequalssignfollowedbyanexpressionthat•evaluates to a value.The initialisation value must be determinable at compile time•

Page 88: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

77

class MyClass{int F1 = 17;}↑ Field initialiser

Ifnoinitialiserisused,thevalueofafieldissetbythecompilertoadefaultvalue,determinedbythetypeofthefield.

To summarise them, though, the default value for each type is 0, and falsefor bool. The default for reference types is null.

Forexample,thefollowingcodedeclaresfourfields.Thefirsttwofieldsareinitialisedimplicitly.Thesecondtwofieldsareinitialisedexplicitlywithinitialisers.class MyClass{int F1; // Initialised to 0 - value typestring F2; // Initialised to null - reference typeint F3 = 25; // Initialised to 25stringF4=“abcd”;//Initialisedto“abcd”}

5.4 Declarations with Multiple FieldsWecandeclaremultiplefieldsofthesametypeinthesamestatementbyseparatingthenameswithcommas.Youcannotmixdifferenttypesinasingledeclaration.Forexample,youcancombinethefourprecedingfielddeclarationsinto two statements, with the exact same semantic result:PROGRAMint F1, F3 = 25;stringF2,F4=“abcd”;NoteUnlikeCandC++,therearenoglobalvariables(i.e.,variablesorfields)declaredoutsideofatype.

Allfieldsbelongtoatype,andmustbedeclaredwithinthetypedeclaration.

5.5 MethodsA method is a named block of executable code that can be executed from many different parts of the program, and even from other programs. When a method is called, or invoked, it executes its code, and then returns to the code that called it. Some methods return a value to the position from which they were called. Methods correspond to member functions in C++. The minimum syntax for declaring a method includes the following components:

Return type: This states the type of value the method returns. If a method does not return a value, the return •typeisspecifiedasvoid.Name: This is the name of the method.•

Parameter list: This consists of at least an empty set of matching parentheses. If there are parameters (which I’ll cover in the next chapter), they are listed between the parentheses.

Method body: This consists of a matching set of curly braces, containing the executable code.•

For example, the following code declares a class with a simple method called PrintNums. From the declaration, you can tell the following about PrintNums:

Itreturnsnovalue;hence,thereturntypeisspecifiedasvoid.•It has an empty parameter list.•

Page 89: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

78

Dot Net Framework (Using C#)

It contains two lines of code in its method body.class SimpleClass{Return type Parameter list↓ ↓void PrintNums ( ){Console.WriteLine(“1”);Console.WriteLine(“2”);}}Note: Unlike C and C++, there are no global functions (i.e., methods or functions) declared outside of a type declaration.

5.6 Creating Variables and Instances of a ClassThe class declaration is just the blueprint from which instances of the class are created. Once a class is declared, you can create instances of the class.

Classesarereferencetypes,which,asyouwillrememberfromthelastchapter,meanthattheyrequirememory•for both the reference to the data and for the actual data.The reference to the data is stored in a variable of the class type. So, to create an instance of the class, you need •tostartbydeclaringavariableoftheclasstype.Ifthevariableisnotinitialised,itsvalueisundefined.

Figure4-2illustrateshowtodefinethevariabletoholdthereference.Atthetopofthecodeontheleftisadeclarationfor class Dealer. Below that is a declaration for class Program, which contains method Main. Main declares variable theDealeroftypeDealer.Sincethevariableisuninitialised,itsvalueisundefined,asshownontherightinthefigure.

class Dealer {...}class program{ static void main() { Dealer theDealer }}

theDealer

Stack

?

Fig. 5.2 Allocating memory for the reference of a class variable

Declaring the variable of the class type allocates the memory to hold the reference, but not the memory to hold the actual data of the class object. To allocate memory for the actual data, you use the new operator.

Thenewoperatorallocatesandinitialisesmemoryforaninstanceofanyspecifiedtype.Itallocatesthememory•from either the stack or the heap, depending on the type.Use the new operator to form an object-creation expression, which consists of the following:•The keyword new.•The name of the type of the instance for which memory is to be allocated.•

Matching parentheses, which might or might not include parameters

Keyword Parenthesesarerequired ↓ ↓ New type name ( )

Page 90: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

79

If the memory allocated is for a reference type, the object-creation expression returns a reference to the allocated and initialised instance of the object in the heap.

This is exactly what you need to allocate and initialise the memory to hold the class instance data. Use the new operator to create an object-creation expression, and assign the value returned by it to the class variable. Here’s an example:

Dealer theDealer; // Declare variable for the reference.theDealer = new Dealer(); // Allocate memory for the class object.

Object-creation expression

ThecodeontheleftinfigurebelowshowsthenewoperatorusedtoallocatememoryandcreateaninstanceofclassDealer,whichisthenassignedtotheclassvariable.Thememorystructureisillustratedinthefigure,totheright of the code.

Stack Heap

class Dealer {...}class App{ static void main() { Dealer theDealer; theDealer-new Dealer(); ... }}

theDealerData

Fig. 5.3 Allocating memory for the data of a class variable

The two steps can be combined by initialising the variable with the object-creation expression.Declare variable.↓Dealer theDealer = new Dealer(); // Declare and initialise.Inthecaseoflocalvariables,butnotfields,youcansimplifythesyntaxabitmorebyhavingthecompilerinferthetype in the declaration part on the left

5.7 Instance MembersA class declaration acts as a blueprint from which you can create as many instances of the class as you like.

Instance members: Each instance of a class is a separate entity that has its own set of the data members, distinct •from the other instances of the same class. These are called instance members since they are associated with an instance of the class.Static members: Instance members are the default, but you can also declare members that are associated with •the class, rather than the instance. These are called static members,

As an example of instance members, the following code shows the poker program with three instances of class Player.Figure5.4showsthateachinstancehasadifferentvaluefortheNamefield.

Page 91: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

80

Dot Net Framework (Using C#)

class Dealer { ... } // Declare classclass Player { // Declare classstring Name; // Field...}

class Program { static void Main() { Dealer theDealer = new Dealer(); Player player1 = new Player(); Player player2 = new Player(); Player player3 = new Player();... }}

...Player3, Player2,Player1the Dealer

Name: Shelley

Name: Susan

Name: Renne

Heap

Fig. 5.4 Instance members are distinct between class objects

5.8 Access ModifiersFrom within a class, any function member can access any other member of the class simply by using that member’s name.

Theaccessmodifierisanoptionalpartofamemberdeclarationthatspecifieswhatotherpartsoftheprogramhasaccesstothemember.Theaccessmodifierisplacedbeforethesimpledeclarationforms.Thefollowingisthesyntaxforfieldsandmethods:

AccessModifierTypeIdentifier;MethodsAccessModifierReturnTypeMethodName(){...}

Page 92: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

81

Thefivecategoriesofmemberaccessarethefollowing.private•public•protected•internal•protected internal•

5.9 Private and Public AccessPrivate members are only accessible from within the class in which they are declared—other classes cannot see or accessthem.Privateaccessisthedefaultaccesslevel—soifamemberisdeclaredwithoutanaccessmodifier,itisa private member.

Youcanalsousetheprivateaccessmodifiertoexplicitlydeclareamemberprivate.•There is no semantic difference between declaring a private member implicitly as opposed to explicitly. The •formsareequivalent.

For example, the following two declarations both specify private int members:

int MyInt1; // Implicitly declared privateprivate int MyInt2; // Explicitly declared private ↑Access modifier

int MyInt1; // Implicitly declared privateprivate int MyInt2; // Explicitly declared private↑AccessmodifierPublicmembersareaccessibletoallotherobjectsintheprogram.Youmustusethepublicaccessmodifiertospecifypublic access.Accessmodifier↓public int MyInt;

5.10 Depicting Public and Private AccessThefiguresinthistextrepresentclassesaslabelledboxes.

The class members are represented as smaller labeled boxes inside the class boxes.•Private members are represented enclosed entirely within their class box.•Public members are represented sticking partially outside their class box.•

5.10.1 Example of Member AccessClassC1declaresbothpublicandprivatefieldsandmethods.Figure4-6illustratesthevisibilityofthemembersof class C1.class C1{intF1; //ImplicitprivatefieldprivateintF2; //ExplicitprivatefieldpublicintF3; //Publicfieldvoid DoCalc() // Implicit private method{...

Page 93: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

82

Dot Net Framework (Using C#)

}public int GetVal() // Public method{...}}

5.10.2 Accessing Members from Inside the ClassAs mentioned before, members of a class can access the other class members by just using their names. For example, thefollowingclassdeclarationshowsthemethodsoftheclassaccessingthefieldsandothermethods.Eventhoughthefieldsandtwoofthemethodsaredeclaredprivate,allthemembersofaclasscanbeaccessedbyanymethod(or any function member) of the class. The code is illustrated below:class DaysTemp{// Fieldsprivate int High = 75;private int Low = 45;// Methodsprivate int GetHigh(){returnHigh;//Accessprivatefield}private int GetLow(){returnLow;//Accessprivatefield}publicfloatAverage(){return (GetHigh() + GetLow()) / 2; // Access private methods}↑↑} Accessing the private methods

5.10.3 Accessing Members from Outside the ClassTo access a public instance member from outside the class, you must include the variable name and the member name, separated by a period (dot). This is called dot-syntax notation; it will be discussed in more detail later. For example, the second line of the following code shows an example of accessing a method from outside the class:DaysTemp myDt = new DaysTemp(); // Create an object of the class.floatfValue=myDt.Average();//Accessitfromoutside.↑ ↑

Variable name Member nameAs an example, the following code declares two classes: DaysTemp and Program.

ThetwofieldsinDaysTemparedeclaredpublic,sotheycanbeaccessedfromoutsidetheclass.•Method Main is a member of class Program. It creates a variable and object of class DaysTemp, and assigns •valuestothefieldsoftheobject.Itthenreadsthevaluesofthefieldsandprintsthemout.

class DaysTemp // Declare class DaysTemp{public int High = 75;public int Low = 45;}class Program // Declare class Program.{

Page 94: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

83

static void Main(){ Variable name↓DaysTemp temp = new DaysTemp(); // Create the object.Variablenameandfield↓temp.High=85;//Assigntothefields.temp.Low=60;Variablenameandfield↓Console.WriteLine(“High:{0}”,temp.High);//Readfromfields.Console.WriteLine(“Low:{0}”,temp.Low);}}This code produces the following output:High: 85Low: 60

5.11 Putting It All TogetherThe following code creates two instances and stores their references in variables named t1 and t2. Example below illustrates t1 and t2 in memory. The code demonstrates the following three actions discussed so far in the use of a class:

Declaring a class•Creating instances of the class•Accessingtheclassmembers(i.e.,writingtoafieldandreadingfromafield)•

class DaysTemp // Declare the class.{publicintHigh,Low;//Declaretheinstancefields.public int Average() // Declare the instance method.{return (High + Low) / 2;}}class Program{static void Main(){// Create two instances of DaysTemp.DaysTemp t1 = new DaysTemp();DaysTemp t2 = new DaysTemp();//Writetothefieldsofeachinstance.t1.High = 76; t1.Low = 57;t2.High = 75; t2.Low = 53;//Readfromthefieldsofeachinstanceandcallamethodof// each instance.Console.WriteLine(“t1:{0},{1},{2}”,t1.High, t1.Low, t1.Average() );Console.WriteLine(“t2:{0},{1},{2}”,t2.High, t2.Low, t2.Average() );↑↑↑} Field Field Method}

Page 95: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

84

Dot Net Framework (Using C#)

This code produces the following output:

t1: 76, 57, 66

t2: 75, 53, 64

5.12 Classes and ObjectsClassesandobjectsplaythekeyroleinobjectorientedprogramming.C#classesandobjectsarebrieflydescribedin the chapter as follows:

5.12.1 ClassesA class is a construct that enables you to create your own custom types by grouping together variables of other types,methodsandevents.Aclassislikeablueprint.Itdefinesthedataandbehaviourofatype.Iftheclassisnot declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable. For more information, see Static Classes and Static Class Members (C# Programming Guide).

Unlike structs, classes support inheritance, a fundamental characteristic of object-oriented programming C# is an object-oriented programming language, and uses classes and structs to implement types such as Windows Forms, userinterfacecontrols,anddatastructures.AtypicalC#applicationconsistsofclassesdefinedbytheprogrammer,combined with classes from the .NET Framework.

C#providesmanypowerfulwaysofdefiningclasses,suchasprovidingdifferentaccesslevels,inheritingfeaturesfromother classes, and allowing the programmer to specify what happens when types are instantiated or destroyed.

Classescanalsobedefinedasgenericthroughtheuseoftypeparametersthatenableclientcodetocustomisetheclassinatype-safeandefficientmanner.Asinglegenericclass,forexampleSystem.Collections.Generic.Listinthe.NET Framework Class Library, can be used by client code to store integers, strings, or any other type of object.

Declaring classesClasses are declared by using the class keyword, as shown in the following example:

public class Customer{ //Fields, properties, methods and events go here...}

The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects fromthisclass.Thenameoftheclassfollowstheclasskeyword.Theremainderofthedefinitionistheclassbody,wherethebehavioranddataaredefined.Fields,properties,methods,andeventsonaclassarecollectivelyreferredto as class members.

5.12.2 ObjectsObjectsareprogrammingconstructsthathavedata,behaviour,andidentity.Objectdataiscontainedinthefields,properties, and events of the object, and object behaviours are defined by themethods and interfaces of theobject.

Objects have identity — two objects with the same set of data are not necessarily the same object.

ObjectsinC#aredefinedthroughclassesandstructs—theseformthesingleblueprintfromwhichallobjectsofthat type operate.

Page 96: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

85

Objects overviewObjects have the following properties:

Everything you use in C# is an object, including Windows Forms and controls.Objectsareinstantiated;thatis,theyarecreatedfromtemplatesdefinedbyclassesandstructs.

Objects use Properties (C# Programming Guide) to obtain and change the information they contain.

Objects often have methods and events that allow them to perform actions.

Visual Studio provides tools for manipulating objects: the Properties Window allows you to change the attributes of objects such as Windows Forms. The Object Browser allows you to examine the contents of an object.

All C# objects inherit from the Object.

Objects, classes and structs have the following properties:

Objects are instances of a given data type. The data type provides a blueprint for the object that is created — or instantiated — when the application is executed.

Newdatatypesaredefinedusingclassesandstructs.

Classes and structs form the building blocks of C# applications, containing code and data. A C# application will always contain of at least one class.

A struct can be considered a lightweight class, ideal for creating data types that store small amounts of data, and does not represent a type that might later be extended via inheritance.

C# classes support inheritance, meaning they can derive from a previously defined class.

5.13 ConstructorsConstructors are class methods that are executed when an object of a class or struct is created. They have the same name as the class or struct, and usually initialise the data members of the new object.

A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer tosetdefaultvalues,limitinstantiation,andwritecodethatisflexibleandeasytoread.

If we do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values as listed in Default Static classes and structs can also have constructors. Classes are declared using the keyword class, as shown in the following example:

class TestClass{//Methods,properties,fields,events,delegates// and nested classes go here.}

5.14 StructA struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:

Page 97: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

86

Dot Net Framework (Using C#)

public struct Book{public decimal price;public string title;public string author;}

5.15 Static Classes and Static Class Members Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

5.16 Static ClassesA class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirementtocreateasetofmethodsthatdonotactoninstancedataandarenotassociatedtoaspecificobjectinyour code. You could use a static class to hold those methods.

The main features of a static class are:They only contain static members•They cannot be instantiated.•They are sealed.•They cannot contain Instance Constructors.•

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state. For more information, see Static Constructors.

5.16.1 When to Use Static ClassesSuppose we have a class CompanyInfo that contains the following methods to get information about the company name and address.

class CompanyInfo{publicstringGetCompanyName(){return“CompanyName”;}publicstringGetCompanyAddress(){return“CompanyAddress”;}//...}

Thesemethodsdonotneedtobeattachedtoaspecificinstanceoftheclass.Therefore,insteadofcreatingunnecessaryinstances of this class, you can declare it as a static class, like this:

Page 98: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

87

static class CompanyInfo{publicstaticstringGetCompanyName(){return“CompanyName”;}publicstaticstringGetCompanyAddress(){return“CompanyAddress”;}//...}

Use a static class as a unit of organisation for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organise the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.

5.16.2 Static MembersAstaticmethod,field,property,oreventiscallableonaclassevenwhennoinstanceoftheclasshasbeencreated.Ifanyinstancesoftheclassarecreated,theycannotbeusedtoaccessthestaticmember.Onlyonecopyofstaticfieldsandeventsexists,andstaticmethodsandpropertiescanonlyaccessstaticfieldsandstaticevents.Staticmembersare often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine.

Static class members are declared using the static keyword before the return type of the member, for example:

public class Automobile{ public static int NumberOfWheels = 4; public static int SizeOfGasTank { get { return 15; } } public static void Drive() { } public static event EventType RunOutOfGas;

//othernon-staticfieldsandproperties...}

Staticmembersareinitialisedbeforethestaticmemberisaccessedforthefirsttime,andbeforethestaticconstructor,if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:

Automobile.Drive();int i = Automobile.NumberOfWheels;

5.16.3 Static ConstructorsA static constructor is used to initialise any static data, or to perform a particular action that needs performed once only.Itiscalledautomaticallybeforethefirstinstanceiscreatedoranystaticmembersarereferenced.

class SimpleClass{ // Static constructor static SimpleClass() {

Page 99: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

88

Dot Net Framework (Using C#)

//... }}

Static constructors have the following properties:Astaticconstructordoesnottakeaccessmodifiersorhaveparameters.•Astaticconstructoriscalledautomaticallytoinitialisetheclassbeforethefirstinstanceiscreatedoranystatic•members are referenced.A static constructor cannot be called directly.•The user has no control on when the static constructor is executed in the program.•Atypicaluseofstaticconstructorsiswhentheclassisusingalogfileandtheconstructorisusedtowriteentries•tothisfile.Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor •can call the LoadLibrary method.

ExampleIn this example, the class Bus has a static constructor and one static member, Drive(). When Drive() is called, the static constructor is invoked to initialise the class.

public class Bus{ // Static constructor: static Bus() {System.Console.WriteLine(“Thestaticconstructorinvoked.”); }

public static void Drive() {System.Console.WriteLine(“TheDrivemethodinvoked.”); }}

class TestBus{ static void Main() { Bus.Drive(); }}

OutputThe static constructor invoked.

The Drive method invoked.

5.16.4 Private Constructors A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class. For example:class NLog

Page 100: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

89

{ // Private Constructor: private NLog() { }

public static double e = System.Math.E; //2.71828...}

The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you don’tuseanaccessmodifierwiththeconstructoritwillstillbeprivatebydefault.However,theprivatemodifierisusually used explicitly to make it clear that the class cannot be instantiated.

Privateconstructorsareusedtopreventthecreationofinstancesofaclasswhentherearenoinstancefieldsormethods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the entire class static. For more information see Static Classes and Static Class Members.

ExampleThe following is an example of a class using a private constructor.

public class Counter{ private Counter() { } public static int currentCount; public static int IncrementCount() { return ++currentCount; }}

class TestCounter{ static void Main() { // If you uncomment the following statement, it will generate // an error because the constructor is inaccessible: // Counter aCounter = new Counter(); // Error

Counter.currentCount = 100; Counter.IncrementCount();System.Console.WriteLine(“Newcount:{0}”,Counter.currentCount); }}

Output

New count: 101Notice that if you uncomment the following statement from the example, it will generate an error because the constructor is inaccessible due to its protection level:

Page 101: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

90

Dot Net Framework (Using C#)

5.16.5 How toWrite a Copy Constructor?Unlike some languages, C# does not provide a copy constructor. If you create a new object and want to copy the values from an existing object, you have to write the appropriate method yourself.

ExampleIn this example, the Person class contains a constructor that takes as the argument another object of type Person. Thecontentsofthefieldsinthisobjectarethenassignedtothefieldsinthenewobject.

class Person{ private string name; private int age; // Copy constructor. public Person(Person previousPerson) { name = previousPerson.name; age = previousPerson.age; }

// Instance constructor. public Person(string name, int age) { this.name = name; this.age = age; }

// Get accessor. public string Details { get {returnname+“is“+age.ToString(); } }}

class TestPerson{ static void Main() { // Create a new person object.Personperson1=newPerson(“George”,40);

// Create another new object, copying person1. Person person2 = new Person(person1); System.Console.WriteLine(person2.Details); }}

Output

George is 40

Page 102: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

91

5.16.6 DestructorsDestructorsperformactionsrequiredtocleanuporreleaseunmanagedresourcesbeforeaninstanceofaclassisdestroyed. The important things to know about destructors are the following:

You can only have a single destructor per class.•Adestructorcannothaveparameters.Adestructorcannothaveaccessibilitymodifiers.•A destructor has the same name as the class, but is preceded by a tilde character (pronounced TIL-duh).•A destructor only acts on instances of classes; hence, there are no static destructors.•

You cannot call a destructor explicitly in your code. Instead, it is called during the garbage collection process, when the garbage collector analyzes your code and determines that there is no longer any path through your code that references the object.

For example, the following code illustrates the syntax for a destructor of a class calledClass1:

Class1{~Class1() // The destructor{CleanupCode}...}Some important guidelines for using destructors are the following:

Don’t implement a destructor if you don’t need one. They can incur performance costs.•A destructor should only release external resources that the object owns. It should not access other objects •because you can’t assume that these objects have not already been collected.

Note:Although there has sometimesbeen a question as towhether destructors shouldbe called “destructors”or “finalizers,” theC#LanguageSpecification,Version 3.0, released at the end of 2007, calls thismethod adestructor.

5.17. Member InitialisationMember initialisation and collection initialisation are two new features that have been introduced with C# 3.0. I likebothalotbecausetheyareveryhandyandreducealotoftyping.Evenmoretheyfinallymakeinitialisationcode look a lot better!

// the traditional C# 2.0 way.Button button1 = new Button();button1.Text=“Thisisasampletext.”;button1.BackColor = Color.White;button1.TextAlign = ContentAlignment.TopCenter;// and with member initialisation (C# 3.0).Button button2 = new Button(){Text=“ThisisasampleText”, BackColor = Color.White, TextAlign = ContentAlignment.TopCenter};

Page 103: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

92

Dot Net Framework (Using C#)

ThiswayofinitialisingthememberssavesusalotoftypingandremindsmealittlebitoftheVB.NET’s“With”keyword.

This feature is very useful if you work with controls. One characteristic of controls is that their constructor never takes any arguments. That allows you to place them on a form (or another control) without having to specify anything: the form’sdesignerjustcreatesthecontrolbycallingthedefaultconstructor.Allthecontrol’ssettingsarethenspecifiedby modifying the properties. If you construct a form (may it be a Windows form or even a web form) in code this addition will save you a lot of time and typing.

5.18 The this ReferenceThe this keyword refers to the current instance of the class. Static member functions do not have a this pointer. The this keyword can be used to access members from within constructors, instance methods, and instance accessors.

The following are common uses of this:

Toqualifymembershiddenbysimilarnames,forexample:public Employee(string name, string alias) { this.name = name; this.alias = alias;}To pass an object as a parameter to other methods, for example:CalcTax(this);To declare indexers, for example:public int this [int param]{ get { return array[param]; } set { array[param] = value; } }

Itisanerrortorefertothisinastaticmethod,staticpropertyaccessor,orvariableinitialiserofafielddeclaration.

Inthisexample,thisisusedtoqualifytheEmployeeclassmembers,nameandalias,whicharehiddenbysimilarnames. It is also used to pass an object to the method CalcTax, which belongs to another class.

The this reference refers to the instance itself. In the following example, the Marry method uses this to set the partner’smatefield:

public class Panda{public Panda Mate;public void Marry (Panda partner){Mate = partner;partner.Mate = this;}}

Page 104: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

93

The this reference also disambiguates a local variable or parameterfromafield.Forexample:public class Test{string name;public Test (string name) { this.name = name; }}The this reference is valid only within nonstatic members of aclass or struct.PropertiesPropertieslooklikefieldsfromtheoutside,butinternallytheycontain logic, like methods do. For example, you can’t tell bylookingatthefollowingcodewhetherCurrentPriceisafieldor a property:Stock msft = new Stock();msft.CurrentPrice = 30;msft.CurrentPrice−=3;Console.WriteLine (msft.CurrentPrice);

5.19 C# Nested ClassWhat is a nested class in the C# language and when should you use one? Nested classes refer to class declarations that occur in other class declarations. Here, we provide an example of using a nested class.

ExampleThe class B here is enclosed inside the declaration of class A. Class B is thus a nested class. Because it has a public accessibilitymodifier,itcanbeaccessedinplacesotherthanclassA’sscope.Inthemainentrypoint,wecreateaninstance of A, and also an instance of A.B. The instance of A does not contain an instance of B; the reverse is also the case.

Program that shows nested class B [C#]

class A{ public int _v1;

public class B { public int _v2; }}

class Program{ static void Main() { A a = new A(); a._v1++;

A.B ab = new A.B(); ab._v2++; }}

Page 105: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

94

Dot Net Framework (Using C#)

5.20 Types Versus InstancesTheimportantpointaboutnestedclassesisthatyouaredeclaringtypes,notmemberfields.Ithappenstobepossibleto enclose one type declaration in another, but they do not merge into the same type. A class can be created inside of another class. A class created inside of another is referred to as nested. To nest a class:Click inside an existing class and type the necessary code for the new class, starting with the class keyword followed by a name and {}

Select the whole class. Right-click the selection and click Surround With. In the list, double-click class Here is an example of a class called Inside that is nested in a class called Outside:

public class Outside{ public class Inside { }}

In the same way, you can nest as many classes as you wish in another class and you can nest as many classes inside of other nested classes if you judge it necessary. Just as you would manage any other class so can you exercise control onanestedclass.Forexample,youcandeclareallnecessaryfields,properties,ormethodsinthenestedclassorinthe nesting class. When you create one class inside of another, there is no special programmatic relationship between both classes: just because a class is nested does not mean that the nested class has immediate access to the members of the nesting class. They are two different classes and they can be used separately as you judge it necessary.

Thenameofanestedclassisnot“visible”outsideofthenestingclass.Toaccessanestedclassoutsideofthenestingclass,youmustqualifythenameofthenestedclassanywhereyouwanttouseit.Forexample,ifyouwanttodeclareanInsidevariablesomewhereintheprogrambutoutsideofOutside,youmustqualifyitsname.

5.21 Constant MembersClasses and structs can declare constants as members. Constants are values which are known at compile time and do not change. (To create a constant value that is initialised at runtime, use the readonly keyword.) Constants are declaredasafield,usingtheconstkeywordbeforethetypeofthefield.Constantsmustbeinitialisedastheyaredeclared. For example:

class Calendar1{ public const int months = 12;}

In this example, the constant months will always be 12, and cannot be changed — even by the class itself. Constants mustbeofanintegraltype(sbyte,byte,short,ushort,int,uint,long,ulong,char,float,double,decimal,bool,orstring), an enumeration, or a reference to null.

Multiple constants of the same type can be declared at the same time, for example:

class Calendar2{ const int months = 12, weeks = 52, days = 365;}

Page 106: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

95

The expression used to initialise a constant can refer to another constant so long as it does not create a circular reference. For example:

class Calendar3{ const int months = 12; const int weeks = 52; const int days = 365;

const double daysPerWeek = days / weeks; const double daysPerMonth = days / months;}

Constantscanbemarkedaspublic,private,protected,internal,orprotectedinternal.Theseaccessmodifiersdefinehowusersoftheclasscanaccesstheconstant.Formoreinformation,seeAccessModifiers.

Constantsareaccessedasiftheywerestaticfields,althoughtheycannotusethestatickeyword.Expressionsthatarenotcontainedwithintheclassdefiningtheconstantmustusetheclassname,aperiod,andthenameoftheconstantto access the constant. For example:

5.22 Read Only MemberThereadonlykeywordisamodifierthatyoucanuseonfields.Whenafielddeclarationincludesareadonlymodifier,assignmentstothefieldsintroducedbythedeclarationcanonlyoccuraspartofthedeclarationorinaconstructorin the same class.

Youcanassignavaluetoareadonlyfieldonlyinthefollowingcontexts:

When the variable is initialised in the declaration, for example:public readonly int y = 5;

Foraninstancefield,intheinstanceconstructorsoftheclassthatcontainsthefielddeclaration,orforastaticfield,inthestaticconstructoroftheclassthatcontainsthefielddeclaration.Thesearealsotheonlycontextsinwhichitisvalidtopassareadonlyfieldasanoutorrefparameter.

Example

// cs_readonly_keyword.cs//Readonlyfieldsusing System;public class ReadOnlyTest { class MyClass { public int x;publicreadonlyinty=25;//Initialiseareadonlyfield public readonly int z;

public MyClass() {z=24;//Initialiseareadonlyinstancefield }

public MyClass(int p1, int p2, int p3)

Page 107: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

96

Dot Net Framework (Using C#)

{ x = p1; y = p2; z = p3; } }

public static void Main() { MyClass p1= new MyClass(11, 21, 32); // OKConsole.WriteLine(“p1:x={0},y={1},z={2}”,p1.x,p1.y,p1.z); MyClass p2 = new MyClass(); p2.x = 55; // OKConsole.WriteLine(“p2:x={0},y={1},z={2}”,p2.x,p2.y,p2.z); }}Output

p1: x=11, y=21, z=32p2: x=55, y=25, z=24

In the preceding example, if you use a statement like this:

p2.y = 66; // Erroryou will get the compiler error message:

The left-hand side of an assignment must be an l-valuewhich is the same error you get when you attempt to assign a value to a constant.

Note:Thereadonlykeywordisdifferentfromtheconstkeyword.Aconstfieldcanonlybeinitialisedatthedeclarationofthefield.Areadonlyfieldcanbeinitialisedeitheratthedeclarationorinaconstructor.Therefore,readonlyfieldscanhavedifferentvaluesdependingontheconstructorused.Also,whileaconstfieldisacompile-timeconstant,thereadonlyfieldcanbeusedforruntimeconstantsasinthefollowingexample:public static readonly uint l1 = (uint) DateTime.Now.Ticks;

5.23 C#’s Const vs. ReadonlyAquicksynopsisonthedifferencesbetween‘const’and‘readonly’inC#:

‘const’:Cannot be staticValue is evaluated at compile timeInitiailised at declaration only

‘readonly’:Can be either instance-level or staticValue is evaluated at run timeCan be initialised in declaration or by code in the constructor

5.24 PropertiesPropertiesaremembersthatprovideaflexiblemechanismtoread,write,orcomputethevaluesofprivatefields.Properties can be used as though they are public data members, but they are actually special methods called accessors. Thisenablesdatatobeaccessedeasilywhilestillprovidingthesafetyandflexibilityofmethods.

Page 108: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

97

In this example, the class TimePeriod stores a time period. Internally the class stores the time in seconds, but a property called Hours is provided that allows a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

Example:class TimePeriod{ private double seconds;

public double Hours { get { return seconds / 3600; } set { seconds = value * 3600; } }}

class Program{ static void Main() { TimePeriod t = new TimePeriod();

// Assigning the Hours property causes the ‘set’ accessor to be called. t.Hours = 24;

// Evaluating the Hours property causes the ‘get’ accessor to be called.System.Console.WriteLine(“Timeinhours:“+t.Hours); }}

OutputTime in hours: 24

Properties overviewProperties enable a class to expose a public way of getting and setting values, while hiding implementation or verificationcode.

A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. For more information, see Accessor Accessibility.

Thevaluekeywordisusedtodefinethevaluebeingassignedbythesetindexer.

Properties that do not implement a set method are read only.

5.25 IndexersIndexers provide a natural syntax for accessing elements in a class or struct that encapsulate a list or dictionary of values. Indexers are similar to properties, but are accessed via an index argument rather than a property name. The string class has an indexer that lets you access each of its char values via an int index:

Syntaxstrings=“hello”;Console.WriteLine (s[0]); // ‘h’Console.WriteLine (s[3]); // ‘l’

Page 109: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

98

Dot Net Framework (Using C#)

The syntax for using indexers is like that for using arrays when the index is an integer type.Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

Inthefollowingexample,agenericclassisdefinedandprovidedwithsimplegetandsetaccessormethodsasameans of assigning and retrieving values. The Program class creates an instance of this class for storing strings.

Indexers overviewFollowing are the properties if indexers

Indexers enable objects to be indexed in a similar manner to arrays.•A get accessor returns a value. A set accessor assigns a value.•Thethiskeywordisusedtodefinetheindexers.•Thevaluekeywordisusedtodefinethevaluebeingassignedbythesetindexer.•Indexersdonothave tobe indexedbyan integervalue; it isup toyouhowtodefine thespecific look-up•mechanism.Indexers can be overloaded.•Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.•

Page 110: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

99

SummaryA class is a construct that enables to create our own custom types by grouping together variables of other types, •methods and events.If the class is not declared as static, client code it can be used by creating objects or instances which are assigned •to a variable.The variable remains in memory until all references to it go out of scope.•Data members, store data associated with the class or an instance of the class.•Function members generally model the functions and actions of the real-world object the class represents.•A C# class can have any number of data and function members.•A running program is a set of objects interacting with each other.•Fields and methods are the most important of the class member types. Fields are data members and methods •are function members.Wecandeclaremultiplefieldsofthesametypeinthesamestatementbyseparatingthenameswithcommas.•Objects are programming constructs that have data, behavior, and identity.•Objectdataiscontainedinthefields,properties,andeventsoftheobject,andobjectbehaviorsaredefinedby•the methods and interfaces of the object.Everything we use in C# is an object, including Windows Forms and controls.•If the memory allocated is for a reference type, the object-creation expression returns a reference to the allocated •and initialised instance of the object in the heap.A struct can be considered a lightweight class, ideal for creating data types that store small amounts of data, •and does not represent a type that might later be extended via inheritance.Static classes and class members are used to create data and functions that can be accessed without creating an •instance of the class.A static constructor is used to initialise any static data, or to perform a particular action that needs performed •once only.A private constructor prevents the class from being instantiated.•Destructorsperformactionsrequiredtocleanuporreleaseunmanagedresourcesbeforeaninstanceofaclass•is destroyed.Adestructorcannothaveparameters.Adestructorcannothaveaccessibilitymodifiers.•The readonly keyword is different from the const keyword.•A get property accessor is used to return the property value, and a set accessor is used to assign a new value.•Thevaluekeywordisusedtodefinethevaluebeingassignedbythesetindexer.•Indexers provide a natural syntax for accessing elements in a class or struct that encapsulate a list or dictionary •of values.Indexers are similar to properties, but are accessed via an index argument rather than a property name.•

Page 111: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

100

Dot Net Framework (Using C#)

ReferencesSolis D., 2008, • Illustrated C# 2008 C# presented clearly, concisely, and visually, Apress Publiscation.Doyle, B., 2011• , C# Programming 3E, Course Technology, Cenage learning.Holzner, S., 2003, • Object-Oriented Programming in C#, [Online] Available at: <http://www.informit.com/articles/article.aspx?p=101373> [Accessed 1 February 2012].Michael Y., • Introduction to Objects and Classes in C#, Part 2, [Online] Available at: <http://function.name/articles/Csharp/23 > [Accessed 1February 2012].Espinosa, E.D., 2008. • Classes and Objects in C#, Part3 [Video Online] Available at: <http://www.youtube.com/watch?v=RlDR-zl5Ook> [Accessed 6 February 2012].Espinosa, E.D., 2008. • Classes and Objects in C#, Part1 [Video Online] Available at: <http://www.youtube.com/watch?v=ANTE74P5j_w> [Accessed 6 February 2012].

Recommended ReadingLiberty, J. and MacDonald, B., 2008, • Learning C# 3.0, 1st ed., O’really publication.Michaelis, M., 2009. • Essential C# 3.0 .NET Framework 3.5, 1st ed., Pearson Education.Sathiaseelan, J. G. R. and Sasikaladevi, N., 2009. • Programming with C# .NET, PHI Publication.

Page 112: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

101

Self Assessment

A _________ is a data structure that can store data and execute code.1. Objecta. Datab. Structc. Classd.

Which of the following statements is true?2. A C# class can have any number of data and function members.a. A C# class can have only one data and function members.b. A C# class can have no data and function members.c. A C# class can have restricted data and function members.d.

The __________ keyword refers to the current instance of the class.3. thisa. evalb. longc. enumd.

The class declaration provides the following:4. The class typea. The members or objectsb. The characteristics of the classc. Characteristics of membersd.

___________ are class methods that are executed when an object of a class or struct is created.5. Initialisera. Constructorb. Destructorsc. Formatspecifierd.

Indexers enable objects to be indexed in a similar manner to ________.6. functionsa. data typesb. arraysc. stackd.

Which of the following statement is true?7. Indexers can have more than one formal parameter.a. Indexer cannot have parametrs.b. Indexers can have only one parameter.c. Inderers have parameters but not formal.d.

Page 113: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

102

Dot Net Framework (Using C#)

The_________keywordisamodifierthatcanbeusedonfields.8. enuma. refb. readonlyc. statd.

A member can be accessed as____________.9. Privatea. Publicb. Protectedc. Internald.

Which of the following statement is true?10. A destructor cannot have parameters.a. A destuctor can have parametrs.b. A construtor can not have parametrs.c. A constructor can have parameters.d.

Page 114: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

103

Chapter VI

Interfaces

Aim

The aim of this chapter is to:

elucidate the interface in C#•

explain the function and action delegate•

definestandardeventpattern•

Objectives

The objectives of this chapter are to:

elucidate implementation of interfaces•

explain application of different over loadable operators•

describe the emergence of standard event patterns•

Learning outcome

At the end of this chapter, you will be able to:

understand explicit interface member implementations•

recognise generic delegate types•

identify non-static function members•

Page 115: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

104

Dot Net Framework (Using C#)

6.1 InterfaceAn interface is a reference type that represents a set of function members, but does not implement them. Other types—classes or structs—can implement interfaces. To get a feeling for interfaces, I’ll start by showing one that isalreadydefined.TheBCLdeclaresaninterfacecalledIComparable,thedeclarationofwhichisshowninthefollowing code. Notice that the interface body contains the declaration of a single method, CompareTo, which takes a single parameter of type object. Although the method has a name, parameters and a return type, there is no implementation. Instead, the implementation is replaced by a semicolon.

Keyword Interface name↓ ↓public interface IComparable{int CompareTo( object obj );} ↑Semicolon in place of method implementation

Figure below illustrates interface IComparable. The CompareTo method is shown in gray to illustrate that it doesn’t contain an implementation.

IComparable

CompareTo( )

Fig. 6.1 Representation of interface IComparable

Although the interface declaration does not provide an implementation for method CompareTo, the .NET documentation of interface IComparable describes what the method should do, in case you create a class or struct that implements the interface. It says that when method CompareTo is called, it should return one of the following values:

A negative value, if the current object is less than the parameter object.•A positive value, if the current object is greater than the parameter object.•Zero,ifthetwoobjectsareconsideredequalinthecomparison.•

Example using the IComparable interfaceTo understand what this means and why it’s useful, let’s start by taking a look at the following code, which takes an unsorted array of integers and sorts them in ascending order.

Thefirstlinecreatesanarrayoffiveintegersthatareinnoparticularorder.•The second line uses the static Sort method of the Array class to sort the elements.•The for each loop prints them out, showing that the integers are now in ascending order.•

var myInt = new [] { 20, 4, 16, 9, 2 }; //Create an array of intsArray.Sort(myInt); //Sort elements by magnitude.foreach (var i in myInt) //Print them out.Console.Write(“{0}“,i);

This code produces the following output:2 4 9 16 20

Page 116: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

105

The Sort method works great on an array of ints, but what would happen if you were to try to use it on one of your own classes, as shown here?

class MyClass // Declare a simple class.

{

public int TheValue;

}

...

MyClass[]mc=newMyClass[5]; //Createanarrayoffiveelements.

... //Create and initialise the elements.

Array.Sort(mc); //Try to use Sort--raises exception

When you try to run this code, it raises an exception. So why did it work for an array of ints, but not for an array of MyClassobjects?ThereasonSortdoesn’tworkwiththearrayofuser-definedobjectsisthatitdoesn’tknowhowtocompareuser-definedobjectsandhowtoranktheirorder.Ithastorelyontheobjectsinthearraytoimplementinterface IComparable. When Sort is running, it compares one element of the array to another by calling one element’s CompareTo method and passing in as a parameter a reference to the other element. The int type implements IComparable, but MyClass does not, so when Sort tries to call the nonexistent CompareTo method of MyClass, it raises an exception.

You can make the Sort method work with objects of type MyClass by making the class implement IComparable. To implement an interface, a class or struct must do two things:

It must list the interface name in its base class list.•It must provide an implementation for each of the interface’s members.•

For example, the following code updates MyClass to implement interface IComparable.Notice the following about the code:

The name of the interface is listed in the base class list of the class declaration.•The class implements a method called CompareTo, whose parameter type and return type match those of the •interface member.MethodCompareToisimplementedfollowingthedefinitiongivenintheinterface’sdocumentation.•

That is, it returns a negative 1, positive 1, or 0, depending on its value compared to the object passed into the method.

Interface name in base class list

class MyClass : IComparable

{public int TheValue;

public int CompareTo(object obj) // Implementation of interface method

{

Page 117: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

106

Dot Net Framework (Using C#)

MyClass mc = (MyClass)obj;

if (this.TheValue < mc.TheValue) return -1;

if (this.TheValue > mc.TheValue) return 1;

return 0;

}

}

Thefigurebelowillustratestheupdatedclass.Thearrowfromthegrayedinterfacemethodtotheclassmethod indicates that the interface method does not contain code, but is implemented by the class-level method.

Method implemented by the class

My classThe value

CompareTo ( ),

IComparableCompareTo ( )

Fig. 6.2 Implementing IComparable in MyClass

Now that MyClass implements IComparable, Sort will work on it as well. It would not, by the way, have been sufficienttojustdeclaretheCompareTomethod—itmustbepartofimplementingtheinterface,whichmeansplacingthe interface name in the base class list. The following shows the complete updated code, which can now use the Sort method to sort an array of MyClass objects. Main creates and initialises an array of MyClass objects and then prints them out. It then calls Sort and prints them out again to show that they have been sorted.

class MyClass : IComparable // Class implements interface.{public int TheValue;public int CompareTo(object obj) // Implement the method.{MyClass mc = (MyClass)obj;if (this.TheValue < mc.TheValue) return -1;if (this.TheValue > mc.TheValue) return 1;return 0;}}class Program{static void PrintOut(string s, MyClass[] mc){Console.Write(s);foreach (var m in mc)Console.Write(“{0}“,m.TheValue);

Page 118: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

107

Console.WriteLine(“”);}static void Main(){var myInt = new [] { 20, 4, 16, 9, 2 };MyClass[] mcArr = new MyClass[5]; // Create array of MyClass objs.for (int i = 0; i < 5; i++) // Initialise the array.{mcArr[i] = new MyClass();mcArr[i].TheValue = myInt[i];}PrintOut(“InitialOrder:“,mcArr); //Printtheinitialarray.Array.Sort(mcArr); // Sort the array.PrintOut(“SortedOrder:“,mcArr); //Printthesortedarray.

This code produces the following output:Initial Order: 20 4 16 9 2Sorted Order: 2 4 9 16 20

6.1.1 Declaring an InterfaceThe previous section used an interface that was already declared in the BCL. In this section, we’ll look at how to declare interfaces. The important things to know about declaring an interface are the following:

An interface declaration cannot contain data members.•An interface declaration can only contain declarations of the following kinds of non static function members:•

Methods �Properties �Events �Indexers �

The declarations of these function members cannot contain any implementation code.•Instead, a semicolon must be used for the body of each member declaration.•By convention, interface names begin with an uppercase I (for example,, ISaveable).•Like classes and structs, interface declarations can also be split into partial interface declarations.•

For example, the following code shows the declaration of an interface with two method members:

Keyword Interface name↓ ↓interface IMyInterface1 Semicolon in place of body{int DoStuff ( int nVar1, long lVar2 );double DoOtherStuff( string s, long x );} ↑Semicolon in place of body

There is an important difference between the accessibility of an interface and the accessibility of interface members:

Page 119: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

108

Dot Net Framework (Using C#)

Aninterfacedeclarationcanhaveanyoftheaccessmodifierspublic,protected,internal,orprivate.•Members of an interface, however, are implicitly public, and no accessmodifiersincluding public, are•allowed.

Accessmodifiersareallowedoninterfaces.↓public interface IMyInterface2{private int Method1( int nVar1, long lVar2 ); // Error} ↑AccessmodifiersareNOTallowedoninterfacemembers.

6.1.2 Implementing an InterfaceOnly classes or structs can implement an interface. As shown in the Sort example, to implement an interface, a class or struct must:

include the name of the interface in its base class list•supply implementations for each of the interface’s members•

For example, the following code shows a new declaration for class MyClass, which implements interface IMyInterface1, declared in the previous section. Notice that the interface name is listed in the base class list after the colon, and that the class provides the actual implementation code for the interface members.

Colon Interface name↓↓class MyClass: IMyInterface1{int DoStuff ( int nVar1, long lVar2 ){ ... } // Implementation codedouble DoOtherStuff( string s, long x ){ ... } // Implementation code}

Some important things to know about implementing interfaces are the following:If a class implements an interface, it must implement all the members of that interface.•If a class is derived from a base class and also implements interfaces, the name of the base class must be listed •in the base class list before any interfaces, as shown here:

class Derived : MyBaseClass, IIfc1, IEnumerable, IEnumerator{...}

Example with a simple interfaceThe following code declares an interface named IIfc1, which contains a single method named PrintOut. Class MyClass implements interface IIfc1 by listing it in its base class list and supplying a method named PrintOut that matches the signature and return type of the interface member. Main creates an object of the class and calls the method from the object.

interface IIfc1 Semicolon in place of body // Declare interface{ ↓void PrintOut(string s);

Page 120: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

109

}Implement interface↓class MyClass : IIfc1 // Declare class{public void PrintOut(string s) // Implementation{Console.WriteLine(“Callingthrough:{0}”,s);}}class Program{static void Main(){MyClass mc = new MyClass(); // Create instancemc.PrintOut(“object.”);//Callmethod}}

This code produces the following outputCalling through: object

6.1.3 Implementing Multiple InterfacesIn the examples shown so far, the classes have implemented a single interface.

A class or struct can implement any number of interfaces.•All the interfaces implemented must be listed in the base class list and separated by commas (following the •base class name, if there is one).

For example, the following code shows class MyData, which implements two interfaces: IDataStore and IDataRetrieve. Program below illustrates the implementation of the multipleinterfaces in class MyData.

interface IDataRetrieve { int GetData(); } // Declare interfaceinterface IDataStore { void SetData( int x ); } // Declare interfaceclass MyData: IDataRetrieve, IDataStore // Declare class{intMem1;//Declarefieldpublic int GetData() { return Mem1; }public void SetData( int x ) { Mem1 = x; }}class Program{static void Main() // Main{MyData data = new MyData();data.SetData( 5 );Console.WriteLine(“Value={0}”,data.GetData());}}

This code produces the following output:Value = 5

Page 121: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

110

Dot Net Framework (Using C#)

My data

Mem1

Get Data ( )

Set Data ( )

IdataRetrive,

GetData ( )

SetData ( )IdataStore

Fig. 6.3 Class implementing multiple interfaces

6.1.4 References to Multiple InterfacesYou saw previously that interfaces are reference types, and that you can get a reference to an interface by casting an object reference to the interface type. If a class implements multiple interfaces, you can get separate references for each one. For example, the following class implements two interfaces with the single method PrintOut. The code in Main calls method PrintOut in three ways:

Through the class object•Through a reference to the IIfc1 interface•Through a reference to the IIfc2 interface•

Study the program below:interface IIfc1 { void PrintOut(string s); } // Declare interfaceinterface IIfc2 { void PrintOut(string s); } // Declare interfaceclass MyClass : IIfc1, IIfc2{//Declare classpublic void PrintOut(string s){Console.WriteLine(“Callingthrough:{0}”,s);}}class Program{static void Main(){MyClass mc = new MyClass( );IIfc1 ifc1 = (IIfc1) mc; // Get ref to IIfc1IIfc2 ifc2 = (IIfc2) mc; // Get ref to IIfc2mc.PrintOut(“object.”); //Callthroughclassobjectifc1.PrintOut(“interface1.”); //CallthroughIIfc1ifc2.PrintOut(“interface2.”); //CallthroughIIfc2}}

This code produces the following output:Calling through: object.Calling through: interface 1.Calling through: interface 2.

Page 122: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

111

Stack

ifc2

ifc1

mc

MyClass

PrintOut ( )

IIfc2PrintOut ( )

IIfc1PrintOut ( )

Fig. 6.4 Separate references to different interfaces in the class

6.1.5 Accessing Explicit Interface Member ImplementationsAn explicit interface member implementation can only be accessed through a reference to the interface. This means that even other class members can’t directly access them. For example, the following code shows the declaration of class MyClass, which implements interface IIfc1 with an explicit implementation. Notice that even Method1, which is also a member of MyClass, can’t directly access the explicit implementation.

ThefirsttwolinesofMethod1producecompileerrorsbecausethemethodistryingtoaccesstheimplementation•directly.Only the last line in Method1 will compile, because it casts the reference to the current object (this) to a reference •to the interface type, and uses that reference to the interface to call the explicit interface implementation.

class MyClass : IIfc1{void IIfc1.PrintOut(string s) // Explicit interface implementation{Console.WriteLine(“IIfc1”);}public void Method1(){PrintOut(“...”); //Compileerrorthis.PrintOut(“...”);//Compileerror((IIfc1)this).PrintOut(“...”);//OK,callmethod} ↑} Cast to a reference to the interface

Thisrestrictionhasanimportantramificationforinheritance.Sinceotherfellowclassmemberscan’tdirectlyaccessexplicit interface member implementations, members of classes derived from the class clearly can’t directly access them either. They must always be accessed through a reference to the interface.

6.1.6 Operator OverloadingTheC#operators,asyou’veseen,aredefinedtoworkusingthepredefinedtypesasoperands.Ifconfrontedwithauser-definedtype,anoperatorsimplywouldnotknowhowtoprocessit.OperatoroverloadingallowsyoutodefinehowtheC#operatorsshouldoperateonoperandsofyouruser-definedtypes.

Operator overloading is only available for classes and structs.•You can overload an operator x for use with your class or struct by declaring a method named operator x that •implements the behavior (for example,, operator +, operator -, etc.).The overload methods for unary operators take a single parameter of the class or struct type.•

Page 123: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

112

Dot Net Framework (Using C#)

The overload methods for binary operators take two parameters, at least one of which must be of the class or struct type.AnoperatoroverloadmethodmustbedeclaredWithbothstaticandpublicmodifiersasamemberoftheclassor struct for which it is an operand

For example, the following code shows two of the overloaded operators of class LimitedInt: the addition operator and the negation operator. You can tell that it is negation and not subtraction because the operator overload method has only a single parameter, and is therefore unary; whereas the subtraction operator is binary.

public static LimitedInt operator -(LimitedInt x) // Unarypublic static LimitedInt operator +(LimitedInt x, double y) // Binaryclass LimitedInt Return{ public static LimitedInt operator + (LimitedInt x, double y){LimitedInt li = new LimitedInt();li.TheValue = x.TheValue + (int)y;return li;}public static LimitedInt operator - (LimitedInt x){// In this strange class, negating a value just sets its value to 0.LimitedInt li = new LimitedInt();li.TheValue = 0;return li;}...}

Restrictions on operator overloadingNot all operators can be overloaded, and there are restrictions on the types of overloading that can be done. The important things you should know about the restrictions on operator overloading are described later in the section. Only the following operators can be overloaded. Prominently missing from the list is the assignment operator.Overloadable unary operators: +, -, !, ~, ++, --, true, false

Overloadable binary operators: +, -, *, /, %, &, |, ^, <<, >>, ==, !=, >, <, >=, <=Theincrementanddecrementoperatorsareoverloadable.Butunlikethepredefinedversions,thereisnodistinctionbetween the pre- and post- usage of the overloaded operator.

You cannot do the following things with operator overloading:Create a new operator•Change the syntax of an operator•Redefinehowanoperatorworksonthepredefinedtypes•Change the precedence or associativity of an operator•

Note Your overloaded operators should conform to the intuitive meanings of the operators.

Example of operator overloadingThe following example shows the overloads of three operators for class LimitedInt: negation, subtraction, and addition.

class LimitedInt {

Page 124: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

113

const int MaxValue = 100;const int MinValue = 0;public static LimitedInt operator -(LimitedInt x){// In this strange class, negating a value just sets its value to 0.LimitedInt li = new LimitedInt( );li.TheValue = 0;return li;}Public static LimitedInt operator -(LimitedInt x, LimitedInt y){LimitedInt li = new LimitedInt();li.TheValue = x.TheValue - y.TheValue;return li;}public static LimitedInt operator +(LimitedInt x, double y){LimitedInt li = new LimitedInt();li.TheValue = x.TheValue + (int)y;return li;}private int _TheValue = 0;public int TheValue{get { return _TheValue; }set{if (value < MinValue)_TheValue = 0;else_TheValue = value > MaxValue? MaxValue: value;}}}class Program {static void Main( ) {LimitedInt li1 = new LimitedInt();LimitedInt li2 = new LimitedInt();LimitedInt li3 = new LimitedInt();li1.TheValue = 10; li2.TheValue = 26;Console.WriteLine(“li1:{0},li2:{1}”,li1.TheValue,li2.TheValue);li3 = -li1;Console.WriteLine(“-{0}={1}”,li1.TheValue,li3.TheValue);li3 = li2 - li1;Console.WriteLine(“{0}-{1}={2}”,li2.TheValue, li1.TheValue, li3.TheValue);li3 = li1 - li2;Console.WriteLine(“{0}-{1}={2}”,li1.TheValue, li2.TheValue, li3.TheValue);

Page 125: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

114

Dot Net Framework (Using C#)

}}This code produces the following output:li1: 10, li2: 26-10 = 026 - 10 = 1610 - 26 = 0

6.2 Overloadable OperatorsC#allowsuser-definedtypestooverloadoperatorsbydefiningstaticmemberfunctionsusingtheoperatorkeyword.Not all operators can be overloaded, however, and others have restrictions, as listed in this table:

Operators Overloadability+, -, !, ~, ++, --, true, false These unary operators can be overloaded+, -, *, /, %, &, |, ^, <<, >> These binary operators can be overloaded==, !=, <, >, <=, >= The comparison operators can be overloaded.&&, || The conditional logical operators cannot be overloaded, but they

are evaluated using & and[] The array indexing operator cannot be overloaded, but you can

defineindexers() Thecastoperatorcannotbeoverloaded,butyoucandefinenew

conversion operators (see explicit and implicit).+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= Assignment operators cannot be overloaded, but +=, for example,

is evaluated using +, which can be overloaded=, ., ?:, ->, new, is, sizeof, typeof These operators cannot be overloaded.

Table 6.1 Overloadable operators

Note: The comparison operators, if overloaded, must be overloaded in pairs; that is, if == is overloaded, != must also be overloaded. The reverse is also true, and similar for < and >, and for <= and >=.

The typeof operatorThe typeof operator returns the System.Type object of any type given as its parameter. From this object, you can learn the characteristics of the type. (There is only one System.Type object for any given type.).The typeof operator is unary.

Operator description‘typeof’ Returns the System.Type object of a given type. The following is an example of the syntax of the typeof operator. Type is a class in the System namespace.

Type t = typeof ( SomeClass )

You cannot overload the typeof operator, as that would defeat the .NET type-safety mechanisms. For example, the following code uses the typeof operator to get information on a class called SomeClass, and print the names of its publicfieldsandmethods.

usingSystem.Reflection;class SomeClass{public int Field1;public int Field2;public void Method1() { }

Page 126: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

115

public int Method2() { return 1; }}class Program{static void Main(){Type t = typeof(SomeClass);FieldInfo[]fi=t.GetFields();MethodInfo[] mi = t.GetMethods();foreach(FieldInfofinfi)Console.WriteLine(“Field:{0}”,f.Name);foreach (MethodInfo m in mi)Console.WriteLine(“Method:{0}”,m.Name);}}

The output of this code is the following:Field : Field1Field : Field2Method: Method1Method: Method2Method: GetTypeMethod: ToStringMethod:EqualsMethod: GetHashCode

The typeof operator is also called by the GetType method, which is available for every object of every type. For example, the following code retrieves the name of the type of the object:class SomeClass{...}class Program{static void Main(){SomeClass s = new SomeClass();Console.WriteLine(“Types:{0}”,s.GetType().Name);}}

This code produces the following output: Type s: SomeClass0

Need for operator overloadingOperator overloading is used for following purposes:

definingOperatoroverloading•overloading unary operators•overloading binary operators•overloading comparison operator•

Page 127: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

116

Dot Net Framework (Using C#)

6.3 Delegates and Events DelegatesA delegate dynamically wires up a method caller to its target method. There are two aspects to a delegate: type and instance.Adelegatetypedefinesaprotocoltowhichthecallerandtargetwillconform,comprisingalistofparametertypes and a return type. A delegate instance is an object that refers to one or more target methods conforming to that protocol. A delegate instance literally acts as a delegate for the caller: the caller invokes the delegate, and then the delegate calls the target method. This indirection decouples the caller from the target method.

A delegate type declaration is preceded by the keyword delegate, but otherwise it resembles an (abstract) method declaration. For example: delegate int Transformer (int x); To create a delegate instance, you can assign a method to a delegate variable:

class Test{static void Main(){Transformert=Square;//Createdelegateinstanceint result = t(3); // Invoke delegateConsole.Write (result); // 9}staticintSquare(intx){returnx*x;}}

Invoking a delegate is just like invoking a method (since the delegate’s purpose is merely to provide a level of indirection): t(3);

ThestatementTransformert=Squareisshorthandfor:Transformert=newTransformer(Square);Andt(3)isshorthand for: t.Invoke (3). A delegate is similar to a callback, a general term that captures constructs such as C function pointers.

Writing plug-in methods with delegatesA delegate variable is assigned a method dynamically. This is useful for writing plug-in methods. In this example, we have a utility method named Transform that applies a transform to each element in an integer array. The Transform method has a delegate parameter, for specifying a plug-in transform.

public delegate int Transformer (int x);class Util

{public static void Transform (int[] values, Transformer t){for (int i = 0; i < values.Length; i++)values[i] = t (values[i]);}}class Test{static void Main( ){int[] values = { 1, 2, 3 };Util.Transform(values,Square);foreach (int i in values)

Page 128: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

117

Console.Write(i+““);//149}staticintSquare(intx){returnx*x;}}

Multicast delegatesAll delegate instances have multicast capability. This means that a delegate instance can reference not just a single target method, but also a list of target methods. The + and += operators combine delegate instances. For example:

SomeDelegate d = SomeMethod1;d += SomeMethod2;

The last line is functionally the same as: d = d + SomeMethod2;

Invoking d will now call both SomeMethod1 and SomeMethod2. Delegates are invoked in the order they are added.

The−and−=operatorsremovetherightdelegateoperandfromtheleftdelegateoperand.Forexample:d−=SomeMethod1;

Invoking d will now cause only SomeMethod2 to be invoked. Calling + or += on a delegate variable with a null valueislegal,asiscalling−=onadelegatevariablewithasingletarget(whichwillresultinthedelegateinstancebeing null).

Note:Delegatesareimmutable,sowhenyoucall+=or−=,you’reinfactcreatinganewdelegateinstanceandassigningit to the existing variable. If a multicast delegate has a nonvoid return type, the caller receives the return value from the last method to be invoked. The preceding methods are still called, but their return values are discarded. In most scenarios in which multicast delegates are used, they have void return types, so this subtlety does not arise.

All delegate types implicitly derive from System.MulticastDele gate, which inherits from System.Delegate. C# compiles+,−,+=,and−=operationsmadeonadelegatetothestaticCombineandRemovemethodsoftheSystem.Delegate class.

6.4 Instance Versus Static Method TargetsWhen a delegate object is assigned to an instance method, the delegate object must maintain a reference not only to the method, but also to the instance to which the method belongs.

The System.Delegate class’s Target property represents this instance (and will be null for a delegate referencing a static method).

6.5 Generic Delegate TypesA delegate type may contain generic type parameters. For example:public delegate T Transformer<T> (T arg);Here’s how we could use this delegate type:staticdoubleSquare(doublex){returnx*x;}static void Main( ){Transformer<double>s=Square;Console.WriteLine (s (3.3)); // 10.89}

Page 129: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

118

Dot Net Framework (Using C#)

6.6 The Func and Action DelegatesWith generic delegates, it becomes possible to write a small set of delegate types that are so general they can work for methods of any return type and any (reasonable) number of arguments. These delegates are the Func and Action delegates,definedintheSystemnamespace(theinandoutannotationsindicatevariance,whichwewillcovershortly):

delegate TResult Func <out TResult> ();delegate TResult Func <in T, out TResult> (T arg);

delegate TResult Func <in T1, in T2, out TResult>(T1 arg1, T2 arg2);... and so on, up to T16delegate void Action ();delegate void Action <in T> (T arg);delegate void Action <in T1, in T2> (T1 arg1, T2 arg2);... and so on, up to T16

These delegates are extremely general. The Transformer delegate in our previous example can be replaced with a Func delegate that takes a single argument of type T and returns asame-typed value:

public static void Transform<T> ( T[] values, Func<T,T> transformer){for (int i = 0; i < values.Length; i++)values[i] = transformer (values[i]);}

The only practical scenarios not covered by these delegates are ref/out and pointer parameters.

Delegate compatibilityDelegate types are all incompatible with each other, even if their signatures are the same:

delegate void D1(); delegate void D2();...D1 d1 = Method1;D2 d2 = d1; // Compile-time errorThe following, however, is permitted:D2 d2 = new D2 (d1);

Delegateinstancesareconsideredequaliftheyhavethesametypeandmethodtarget(s).Formulticastdelegates,theorderofthemethodtargetsissignificant.

6.7 Return Type VarianceWhenyoucallamethod,youmaygetbackatypethatismorespecificthanwhatyouaskedfor.Thisisordinarypolymorphicbehavior.Inkeepingwiththis,adelegatetargetmethodmayreturnamorespecifictypethandescribedby the delegate. This is covariance, and has been supported since C# 2.0:

delegate object ObjectRetriever();...static void Main(){ObjectRetriever o = new ObjectRetriever (GetString);

Page 130: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

119

object result = o();Console.WriteLine (result); // hello}staticstringGetString(){return“hello”;}

The ObjectRetriever expects to get back an object, but an object subclass will also do because delegate return types are covariant.

Parameter varianceWhenyoucall amethod,youcan supplyarguments thathavemore specific types than theparametersof thatmethod.Thisisordinarypolymorphicbehavior.Inkeepingwiththis,adelegatetargetmethodmayhavelessspecificparameter types than described by the delegate. This is called contravariance:

delegate void StringAction (string s);...static void Main(){StringAction sa = new StringAction (ActOnObject);sa(“hello”);}static void ActOnObject (object o){Console.WriteLine (o); // hello}

The standard event pattern is designed to help you leverage delegate parameter contravariance through its use of the common EventArgs base class. For example, you can have a single method invoked by two different delegates, one passing a MouseEventArgs and the other passing a KeyEventArgs.

6.8 Type Parameter Variance for Generic Delegates In“Generics”onpage92,wesawhowtypeparameterscanbecovariantandcontravariantforgenericinterfaces.ThesamecapabilityalsoexistsforgenericdelegatesinC#4.0.Ifyou’redefiningagenericdelegatetype,it’sgoodpractice to:

Mark a type parameter used only on the return value as covariant (out).•Mark any type parameters used only on parameters as Contra variant (in).•

Doing so allows conversions to work naturally by respecting inheritance relationships between types. The following delegate(definedintheSystemnamespace)iscovariantfor

TResult:delegate TResult Func<out TResult>();allowing:Func<string> x = ...;Func<object> y = x;

The following delegate (defined in the System namespace) is contra variant for T:delegate void Action<in T> (T arg);allowing:Action<object> x = ...;Action<string> y = x;

Page 131: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

120

Dot Net Framework (Using C#)

EventsWhen using delegates, two emergent roles commonly appear:

broadcaster •subscriber•

Thebroadcasterisatypethatcontainsadelegatefield.Thebroadcasterdecideswhentobroadcast,byinvokingthedelegate. The subscribers are the method target recipients. A subscriber decides when to start and stop listening, bycalling+=and−=onthebroadcaster’sdelegate.Asubscriberdoesnotknowabout,or interferewith,othersubscribers. Events are a language feature that formalizes this pattern. An event is a construct that exposes just the subsetofdelegatefeaturesrequiredforthebroadcaster/subscribermodel.Themainpurposeofeventsistopreventsubscribers from interfering with each other. The easiest way to declare an event is to put the event keyword in front of a delegate member:

public class Broadcaster{public event ProgressReporter Progress;}

Code within the Broadcaster type has full access to Progress and can treat it as a delegate. Code outside of Broadcaster canonlyperform+=and−=operationsontheProgressevent.Inthefollowingexample,theStockclassfiresitsPriceChangedeventeverytimethePriceoftheStockchanges:

public delegate void PriceChangedHandler(decimal oldPrice, decimal newPrice);public class Stock{string symbol; decimal price;public Stock (string symbol) { this.symbol = symbol; }public event PriceChangedHandler PriceChanged;public decimal Price{get { return price; }set{if (price == value) return; // Fire event if invocation list isn’t empty:if (PriceChanged != null)PriceChanged (price, value);price = value;}}}IfweremovetheeventkeywordfromourexamplesothatPriceChangedbecomesanordinarydelegatefield,ourexample would give the same results. However, Stock would be less robust, in that subscribers could do the following things to interfere with each other:

Replace other subscribers by reassigning PriceChanged (instead of using the += operator).Clear all subscribers (by setting PriceChanged to null).•Broadcast to other subscribers by invoking the delegate.•Events can be virtual, overridden, abstract, or sealed. They can also be static.•

Page 132: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

121

Standard event patternThe.NETFrameworkdefinesastandardpatternforwritingevents.ItspurposeistoprovideconsistencyacrossbothFramework and user code. Here is the preceding example refactored with this pattern:

public class PriceChangedEventArgs : EventArgs{public readonly decimal LastPrice, NewPrice;public PriceChangedEventArgs (decimal lastPrice,decimal newPrice){LastPrice = lastPrice; NewPrice = newPrice;

}}public class Stock{string symbol; decimal price;public Stock (string symbol) { this.symbol = symbol; }public event EventHandler<PriceChangedEventArgs>PriceChanged;protected virtual void OnPriceChanged(PriceChangedEventArgs e){if (PriceChanged != null) PriceChanged (this, e);}public decimal Price{get { return price; }set{if (price == value) return;OnPriceChanged (new PriceChangedEventArgs (price,value));price = value;}}}

AtthecoreofthestandardeventpatternisSystem.EventArgs:apredefinedFrameworkclasswithnomembers(otherthan the static Empty property). EventArgs is a base class for conveying information for an event. In this example, wesubclassEventArgstoconveytheoldandnewpriceswhenaPriceChangedeventisfired.ThegenericSystem.EventHandlerdelegateisalsopartofthe.NETFrameworkandisdefinedasfollows:

public delegate void EventHandler<TEventArgs>(object source, TEventArgs e)where TEventArgs : EventArgs;

Note: Before C# 2.0 (when generics were added to the language), the solution was to instead write a custom eventhandling delegate for each EventArgs type, as follows:

delegate void PriceChangedHandler(object sender, PriceChangedEventArgs e);

Page 133: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

122

Dot Net Framework (Using C#)

For historical reasons, most events within the Framework use delegates defined in this way.Aprotectedvirtualmethod,namedOn-event-name,centralisesfiringoftheevent.Thisallowssubclassestofiretheevent(whichisusuallydesirable)andalsoallowssubclassestoinsertcodebeforeandaftertheeventisfired.

Here’s how we could use our Stock class:static void Main( ){Stockstock=newStock(“THPW”);stock.Price = 27.10M;stock.PriceChanged += stock_PriceChanged;stock.Price = 31.59M;}static void stock_PriceChanged(object sender, PriceChangedEventArgs e){if ((e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M)Console.WriteLine(“Alert,10%priceincrease!”);}

For events that don’t carry additional information, the Framework also provides a nongeneric EventHandler delegate.WecandemonstratethisbyrewritingourStockclasssuchthatthePriceChangedeventfiresaftertheprice changes.

This means that no additional information need be transmitted with the event:public class Stock{string symbol; decimal price;public Stock (string symbol) {this.symbol = symbol;}public event EventHandler PriceChanged;protected virtual void OnPriceChanged (EventArgs e){if (PriceChanged != null) PriceChanged (this, e);}public decimal Price{get { return price; }set{if (price == value) return;price = value;OnPriceChanged (EventArgs.Empty);}}}Note that we also used the EventArgs.Empty property—this saves instantiating an instance of EventArgs.

Event accessorsAnevent’saccessorsaretheimplementationsofit’s+=and−=functions.Bydefault,accessorsareimplementedimplicitly by the compiler. Consider this event declaration: public event EventHandler PriceChanged;

Page 134: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

123

The compiler converts this to the following:Aprivatedelegatefield.

Apublicpairofeventaccessorfunctions,whoseimplementationsforwardthe+=and−=operationstotheprivatedelegatefield.

You can take over this process by defining explicit event accessors.Here’s amanual implementation of thePriceChanged event from our previous example:

EventHandler _priceChanged; // Private delegatepublic event EventHandler PriceChanged{add { _priceChanged += value; }remove{_priceChanged−=value;}}

This example is functionally identical to C#’s default accessor implementation (except that C# also ensures thread safetyaroundupdatingthedelegate).Bydefiningeventaccessorsourselves,weinstructC#nottogeneratedefaultfieldandaccessorlogic.Withexpliciteventaccessors,youcanapplymorecomplexstrategiestothestorageandaccess of the underlying delegate. This is useful when the event accessors are merely relays for another class that is broadcasting the event, or when explicitly implementing an interface that declares an event:

public interface IFoo { event EventHandler Ev; }class Foo : IFoo{EventHandler ev;event EventHandler IFoo.Ev{add{ev+=value;}remove{ev−=value;}}}

Page 135: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

124

Dot Net Framework (Using C#)

SummaryAn interface is a reference type that represents a set of function members, but does not implement them.•The BCL declares an interface called IComparable. •Only classes or structs can implement an interface.•A class or struct can implement any number of interfaces.•Not all operators can be overloaded, and there are restrictions on the types of overloading that can be done.•When a delegate object is assigned to an instance method, the delegate object must maintain a reference not •only to the method, but also to the instance to which the method belongs.C#allowsuser-defined types tooverloadoperatorsbydefiningstaticmember functionsusing theoperator•keyword.Like classes and structs, interface declarations can also be split into partial interface declarations.•Aneventisaconstructthatexposesjustthesubsetofdelegatefeaturesrequiredforthebroadcaster/subscriber•model.The.NETFrameworkdefinesastandardpatternforwritingevents.Itspurposeistoprovideconsistencyacross•both Framework and user code.If a class implements multiple interfaces, you can get separate references for each one.•The Transform method has a delegate parameter, for specifying a plug-in transform.•A delegate type declaration is preceded by the keyword delegate, but otherwise it resembles an (abstract) method •declaration.

ReferencesWilliam, R., 2002. • Pure C# A Code-Intensive Premium Reference, 1st ed., SAMS Publication.Telles, M. and Kogent solution, 2008. • C# 2005 Programming Black Book, Dreamtech Publication. Ed Guzman., 2010. • Delegates in C#- Attempt to Look Inside- Part 3, [Online] Available at: <http://www.codeproject.com/Articles/115710/Delegates-in-C-Attempt-to-Look-Inside-Part-3> [Accessed 1 February 2010].Dot Net Perls, • C# Operator Overloading. [Online] Available at: <http://www.dotnetperls.com/operator> [Accessed 1 February 2010].QuackWare, 2011. • Inheritance, Abstract Classes, and Interfaces - C# C Sharp Visual Studio 2010, [Video Online] Available at: <http://www.youtube.com/watch?v=2fyc1QW-FXI&feature=results_main&playnext=1&list=PL0799377C5CCA5299> [Accessed 3 February 2012].ProgrammingVideos, 2010. • C# Tutorial - 18 - Interface, [Video Online] Available at: <http://www.youtube.com/watch?v=oHKec9XFZdc> [Accessed 3 February 2012].

Recommended ReadingSchildt, H., 2010. • The Complete Reference C# reference 4.0, 2nd ed., Tata McGRaw Hill.Hunt, J., 2002. • Guide to C# And Object Orientation, Springer Publication.Steven, J. M., 2009. • Design Patterns in C#, Pearson Education.

Page 136: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

125

Self Assessment

Which of the following statements is true?1. Only classes or structs can implement an interface.a. Only classes can implement an interface.b. Only structs can implement an interfacec. Neither classes nor structs can implement an interface.d.

An interface declaration can contain declarations of the kinds:2. eventsa. delegatesb. multiplexersc. indexersd.

An interface is ___________ type that represents a set of function members.3. Valuea. Intb. Boolc. Referenced.

Which of the following statements is true?4. A class or struct can implement any number of interfaces.a. A class or struct can implement only one interface.b. Neither class nor struct can implement interface.c. Only class can implement interface.d.

The BCL declares an interface called ___________.5. IComparablea. Comparableb. Non comparablec. Dissimilar d.

An ________ interface member implementation can only be accessed through a reference to the interface.6. implicita. explicitb. base c. classd.

___________is only available for classes and structs.7. Constructora. Delegatesb. Operator overloadingc. Eventd.

Page 137: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

126

Dot Net Framework (Using C#)

A delegate type declaration is preceded by the keyword ___________.8. delegatea. delb. deletec. delegatetyped.

All delegate instances have __________capability.9. Overloadinga. Multicastb. Convergencec. Castingd.

Which of the following statements is true?10. An interface declaration cannot contain data members.a. An interface member can contain data members.b. An interface member can contain data members but restricted.c. An interface member always contains data members.d.

Page 138: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

127

Chapter VII

Inheritance and Polymorphism

Aim

The aim of this chapter is to:

introduce the types of inheritance•

elucidate overridden methods of classes•

explain the concepts such as ‘inheritance’ and ‘polymorphism’ •

Objectives

The objectives of this chapter are to:

explain encapsulation’•

describe the method to declare abstract classes and abstract members•

elucidate polymorphic programming in .Net•

Learning outcome

At the end of this chapter, you will be able to:

understand how classes are prevented from being inherited•

identify casting and reference conversion •

recognise multilevel inheritance and its types •

Page 139: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

128

Dot Net Framework (Using C#)

7.1 Overriding MethodsTwoadditionalmethodsareaddedtothePersonclassandshowninthefollowingexample.ThefirstoverridestheobjectToString()method.Whenyouoverrideamethod,youreplacethemethoddefinedatahigherlevelwithanewdefinitionorbehavior.NoticethatthekeywordoverrideisaddedontotheToString()methodheadingandvirtual is added onto the GetSleepAmt( ) method heading. Placing virtual in the method heading allows the method to be overridden.

ExamplePublicoverridestringToString() //DefinedinPerson{ReturnfirstName+““+lastName;}Public virtual int GetSleepAmt( ){ return 8;}

Overriding a method differs from overloading a method. An overridden method must have exactly the same signature asthemethoditisoverriding.Newfunctionalityisnormallydefinedwithoverriddenmethods.Overloadedmethodsmusthaveadifferentsignaturethanotherswiththesamename.Overloadedmethodsareusuallydefinedtoperforma similar behaviour, but with different data types.

Using the override keywordThe override keyword allows a method to provide a new implementation of a method inherited from a base class. When you override a method, the signature of the methods must match. To override a base method, the base method mustbedefinedasvirtual,abstract,oroverride.Figure10-4showsthesignaturefortheToString()methodthatbelongs to the object class. This is taken from the online documentation in Visual Studio.

[C#]public virtual string ToString();

Fig. 7.1 ToString() signature

7.2 Abstract ClassesWith the preceding examples, you can instantiate objects of the Person class in the same manner as you construct objectsoftheStudentclass.Mostmodernlanguages,includingC#,allowyoutoaddanabstractmodifiertoclassesthat prohibits other classes from instantiating objects of a base class. You can still inherit characteristics from this base class in subclasses, which enables you to ensure a certain amount of identical functionality from subclasses. This base class can have data and method members. To create an abstract class in C#, you write:

[accessmodifier]abstractclassClassIdentifier{}//Baseclass

Whenyouusetheabstractmodifierkeywordwithaclass,youmarkitsothattheclasscanbeusedonlyasthebaseclass from which other classes can be derived. No objects can then be instantiated of the base class type. To indicate that the Person class is intended to be used only as a base class of other classes, you add the abstract keyword, as shown in the example below.

Example

Page 140: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

129

Public abstract class Person{ . . . }

Aftertheabstractmodifierisadded,anyattempttoinstantiateobjectsofthePersonclassresultsinthefollowingsyntaxerror:“Cannotcreateaninstanceof theabstractclassor interfacePersonNamespace.Person.”Addingtheabstract keyword does not keep you from instantiating classes derived from the Person class, such as the Student class.

7.3 Abstract MethodsAn abstract class may contain one or more abstract methods. Abstract methods are only permitted in abstract classes. An abstract method is one that does not include the implementation details for the method. The method has no body. The implementation details of the method are left up to the classes that are derived from the base abstract class.

The syntax for creating an abstract method is as follows:

[accessmodifier]abstractreturnTypeMethodIdentifier([parameterlist]); //No{}

The declaration for an abstract method ends with a semicolon following the signature. No braces ({ }) are used withthemethod.Example10-17illustratesdefiningPersonasanabstractclasswithanabstractmethodnamedGetExerciseHabits( ).

ExamplePublic abstract class Person{Public abstract string GetExerciseHabits( ); // No{}// Additional statements would be added

Now any and every class that derives from the Person class must provide the implementation details for the GetExerciseHabits( ) method. That is what adding the abstract keyword does. It is like signing a contract. If you derive from an abstract base class, you sign a contract that details how to implement its abstract methods.

NoteYoureceiveasyntaxerrorifyouusethekeywordstaticorvirtualwhendefininganabstractmethod.Thereisan implicit assumption that the method will be overridden; thus, the keyword virtual is unnecessary.

If the abstract class includes more than one abstract method, derived classes must provide implementation details foreveryabstractmethodincludedinthebaseclass.Abstractclassescanincluderegulardatafieldmembers,regularmethods, and virtual methods in addition to abstract methods. Remember that a virtual method tags the method as being capable of being overridden in a derived class. This does not mean that all derived classes have to provide new implementation details for those tagged as virtual, just that they can. Other than the fact that the derived class mustimplementallabstractmethods,noadditionalspecialkeywordsareusedwhenanewclassisdefinedtoinheritfrom the abstract base class.

All .NET languages only support single inheritance, which means that a class can extend or derive from at most one class. One-way languages such as C# and Java work around this is by implementing multiple interfaces, which are the topic for the next section.

Note: C++ permits multiple inheritances. A class can extend from more than one base class in C++. This is not possible in C#, Java, J#, or any of the managed .NET languages.

Page 141: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

130

Dot Net Framework (Using C#)

7.4 Sealed Classes Classes can be declared as sealed. This is accomplished by putting the keyword sealed before the keyword class in theclassdefinition.Forexample:

public sealed class D{ // Class members here.}

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.

Aclassmember,method,field,property,orevent,onaderivedclassthatisoverridingavirtualmemberofthebaseclass can declare that member as sealed. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration. For example:

Sealedclassesareusedtorestricttheinheritancefeatureofobjectorientedprogramming.Onceaclassisdefinedas sealed class, this class cannot be inherited.

InC#,thesealedmodifierisusedtodefineaclassassealed.InVisualBasic.NET,NotInheritablekeywordservesthe purpose of sealed. If a class is derived from a sealed class, compiler throws an error. If you have ever noticed, structsaresealed.Youcannotderiveaclassfromastruct.ThefollowingclassdefinitiondefinesasealedclassinC#:

// Sealed classsealed class SealedClass{ ... }

In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine.Butifyoutrytoderiveaclassfromsealedclass,youwillgetanerror.

using System;class Class1{static void Main(string[] args){SealedClass sealedCls = new SealedClass();int total = sealedCls.Add(4, 5);Console.WriteLine(“Total=“+total.ToString());}} // Sealed classsealed class SealedClass{public int Add(int x, int y){return x + y;}}

Page 142: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

131

Why sealed classes? We just saw how to create and use a sealed class. The main purpose of a sealed class is to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.Drawing namespace. The Pens class represent the pens for standard colors. This class has only static members. For example, Pens. Blue represents a pen with blue color. Similarly, the Brushes class represents standard brushes. The Brushes. Blue represents a brush with blue color. So when you’re designing your application, you may keep in mind that you have sealed classes to seal user’s boundaries. In the next article of this series, I will discuss some usage of abstract classes.

7.5 Preventing InheritanceHow to prevent a class from being inherited? Sealed in C#?In order to prevent a class in C# from being inherited, the sealed keyword is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class. Code below...

C# Examplesealed class ClassA{public int x; public int y;}NoclasscaninheritfromClassAdefinedabove.InstancesofClassAmaybecreatedanditsmembersmaythenbeaccessed, but nothing like the code below is possible.

class DerivedClass: ClassA {} // Error

7.6 Inheritance and Polymorphism Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (or pillars) of object-oriented programming. Inheritance enables you to create new classes that reuse, extend, and modify the behaviorthatisdefinedinotherclasses.Theclasswhosemembersareinheritediscalledthebaseclass,andtheclass that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.

Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance.PolymorphismisaGreekwordthatmeans“many-shaped”andithastwodistinctaspects:

At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object’s declared type is no longer identical to its run-time type.

Baseclassesmaydefineandimplementvirtualmethods,andderivedclassescanoverridethem,whichmeanstheyprovidetheirowndefinitionandimplementation.Atrun-time,whenclientcodecallsthemethod,theCLRlooksupthe run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class’s version of the method to be executed.

7.6.1 InheritanceA class can inherit from another class to extend or customize the original class. Inheriting from a class lets you reuse the functionality in that class instead of building it from scratch.A class can inherit from only a single class, but can itself be inherited by many classes, thus, forming a class hierarchy.

Page 143: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

132

Dot Net Framework (Using C#)

Inthisexample,westartbydefiningaclasscalledAsset:publicclassAsset{publicstringName;}Next,wedefineclassescalledStockandHouse,whichwill inheritfrom

Asset. Stock and House get everything an Asset has,plusanyadditionalmembersthattheydefine:public class Stock : Asset // inherits from Asset{public long SharesOwned;}public class House : Asset // inherits from Asset{public decimal Mortgage;}

Here’s how we can use these classes:Stockmsft=newStock{Name=”MSFT”,SharesOwned=1000};Console.WriteLine (msft.Name); // MSFTConsole.WriteLine (msft.SharesOwned); // 1000Housemansion=newHouse{Name=”Mansion”,Mortgage=250000};Console.WriteLine (mansion.Name); // MansionConsole.WriteLine (mansion.Mortgage); // 250000

The subclasses, Stock and House, inherit the Name property from the base class, Asset.

7.6.2 Multilevel InheritanceMultiple inheritance is a feature of some object-oriented computer programming languages in which a class can inheritbehaviorsandfeaturesfrommorethanonesuperclass.Inheritancecanbeclassifiedinto5typesaslistedbelow.

Single inheritanceWhen a single derived class is created from a single base class then the inheritance is called as single inheritance.

Base

Derlved

Fig. 7.2 Single inheritance

Hierarchical inheritanceWhen more than one derived class are created from a single base class, then that inheritance is called as hierarchical inheritance.

Page 144: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

133

Base

Derived1 Derived1

Fig. 7.3 Hierarchical inheritance

Multi level inheritanceWhen a derived class is created from another derived class, then that inheritance is called as multi level inheritance.

Base

Derived1

Derived2

Fig. 7.4 Multi-level inheritance

Page 145: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

134

Dot Net Framework (Using C#)

Hybrid inheritanceAny combination of single, hierarchical and multi level inheritances is called as hybrid inheritance.

Base

Derived2 Derived2

Derived1

Fig. 7.5 Hybrid inheritance

Multiple inheritanceWhen a derived class is created from more than one base class then that inheritance is called as multiple inheritance. But, multiple inheritance is not supported by .net using classes and can be done using interfaces.

Base1 Base2

Derived

Fig. 7.6 Multiple inheritance

Handling the complexity that causes due to multiple inheritance is very complex. Hence it was not supported in dotnet with class and it can be done with interface

7.6.3 EncapsulationEncapsulation is one of the fundamental principles of object-oriented programming. Encapsulation is a process of hiding all the internal details of an object from the outside world. Encapsulation has the ability to hide its data and methodsfromoutsidetheworldandonlyexposedataandmethodsthatarerequired.

Encapsulation is a protective barrier that prevents the code and data being randomly accessed by other code or •by outside the class.It gives usmaintainability, flexibility and extensibility to our code.Encapsulationmakes implementation•inaccessible to other parts of the program and protect from whatever actions might be taken outside the function or class.It provides a way to protect data from accidental corruption•

Page 146: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

135

It hides information within an object•Itisthetechniqueorprocessofmakingthefieldsinaclassprivateandprovidingaccesstothefieldsusing•public methodsIt gives you the ability to validate the values before the object user change or obtain the value•Itallowsustocreatea“blackbox”andprotectsanobjectsinternalstatefromcorruptionbyitsclients.•

7.6.4 PolymorphismReferences are polymorphic. This means a variable of type x can refer to an object that subclasses x. For instance, consider the following method:

public static void Display (Asset asset){System.Console.WriteLine (asset.Name);}

This method can display both a Stock and a House, since they are both Assets. Polymorphism works on the basis that subclasses (Stock and House) have all the features of their base class(Asset). The converse, however, is not true. If Display was rewritten to accept a House, you could not pass in an Asset.

7.7 Casting and Reference ConversionsAn object reference can be:

Implicitly upcast to a base class reference•Explicitly downcast to a subclass reference•

Upcasting and downcasting between compatible reference types performs reference conversions: a new reference is created that points to the same object. An upcast always succeeds; a downcast succeeds only if the object is suitably typed.

7.7.1 UpcastingAn upcast operation creates a base class reference from a subclass reference. For example:Stock msft = new Stock(); // From previous exampleAsset a = msft; // Upcast

After the upcast, variable a still references the same Stock object as variable msft. The object being referenced is not itself altered or converted: Console.WriteLine (a == msft); // True

Although a and msft refer to the identical object, a has a more restrictive view on that object:Console.WriteLine (a.Name); // OKConsole.WriteLine (a.SharesOwned); // Error

The last line generates a compile-time error because the variable a is of type Asset, even though it refers to an object oftypeStock.TogettoitsSharesOwnedfield,youmustowncasttheAssettoaStock.

7.7.2 DowncastingA downcast operation creates a subclass reference from a base class reference. For example:Stock msft = new Stock();Asset a = msft; // UpcastStock s = (Stock)a; // DowncastConsole.WriteLine (s.SharesOwned); // <No error>Console.WriteLine (s == a); // True

Page 147: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

136

Dot Net Framework (Using C#)

Console.WriteLine (s == msft); // TrueAs with an upcast, only references are affected—not the underlyingobject.Adowncastrequiresanexplicitcastbecauseit can potentially fail at runtime:House h = new House();Asset a = h; // Upcast always succeedsStock s = (Stock)a; // Downcast fails: a is not a StockIf a downcast fails, an InvalidCastException is thrown. This is an example of runtime type checking

7.7.3 PolymorphismPolymorphism is the ability for classes to provide different implementations of methods that are called by the same name. You already understand and use polymorphism in your everyday life when you determine what situation or object is being used with a verb to determine the verb’s true behavior. For example, by itself the meaning of the verb“drive”isvague.Drivingacardiffersfromdrivinganail,drivingaboat,ordrivingsomeonecrazy.Onlywhenyouput“drive”incontextdoyouknowwhatbehaviororactivityisassociatedwithit.

Youhavealsoexperiencedtheuseofpolymorphisminyourprogramsanumberoftimes.OnequickexampleiswiththeToString()method.RememberthatthismethodisdefinedasoneofthefourmethodsoftheObjectclass.Thismeansthatforeveryclassin.NET,bothuser-definedandFrameworkclasseshaveaToString()method.Basedonwhat kind of object calls the ToString ( ) method, it performs a different function. The end result is to convert some object to its string representation. Converting an integer to a string is a different activity than converting a single character to a string. You can think of it as having a number of different implementations, and the implementation is determined by the type of object that calls it. Example 10-23 shows two calls to the ToString( ) method, which were included in the PresentationGUI class.

Learn the following Example://CallsoverriddenToString()definedinersonclass//Returnsthefirstname,aspace,andthelastnamethis.txtBxName.Text = aStudent.ToString( );//CallsToString()definedinobjectclass// Returns a number representing age in a string formatthis.txtBxAge.Text = aStudent.Age.ToString( );

Asisnotedinthecomment,thefirstcalltotheToString()methodcallsthemethoddefinedinthePersonclass.Remember that the method overrides the object’s ToString( ).This implementation of ToString( ) was to concatenate thefirstandlastnamewithaspacebetweenthem.TheCLRrecognizedthatitshouldusethismethodbecauseitwascalled with a Student object. Student did not contain an implementation of the ToString( ) method; thus, the CLR looked next to the class from which it had been derived, the Person class.

The second call to the ToString( ) method does not use the Person class’s implementation. Notice that this call is made with an int object. The Age property returns an int. Thus, based on the object making the call, the ToString( ) method from the Object class is called. Polymorphism allows a method of a class to be called without regard to what specificimplementationitprovides.Thus,in.NET,polymorphismisimplementedthroughinterfaces,inheritance,and the use of abstract classes.

7.8 Polymorphic Programming in .NETAs you saw, multiple classes can implement the same interface or implement more than one interface. The interface describes the methods and the types of parameters, each method member needs to receive and return, but it leaves the actual details of the body of the method up to the classes that implement the interface. Every class that implements the interface may have a completely different behavior. The method name is the same in all the classes implementing the interface, but the functionality can be much different from one class to another.

Page 148: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

137

The black box concept of object-oriented development comes into play here. You do not have to know how the method goes about doing its work. All you have to know is what arguments to send, if any, and what you expect to beaccomplishedwhentheobjectfinishesitswork.Thatmaybeareturnvalueorjustanindicationthatthemethodis complete.

Through inheritance, polymorphism is made possible by allowing classes to override base class members. This makes dynamic binding possible. The CLR determines which method to call at run time based on which object calls the method. Marking the method with the virtual keyword enables derived classes to write their own functionality for the method.

Remember that a class does not have to override a virtual method. The class can choose to use the base class’s implementation. Because an abstract class cannot be instantiated, the features of both interfaces and inheritance come into play with polymorphic programming. Through the use of abstract classes, classes that derive from them are forced to include implementation details for any abstract method. Unlike interfaces, which simply provide the heading for the methods that have to be implemented, some or all of the members of an abstract class can be implemented.

Abstract classes can also include data members, properties, events, and methods.The methods can be marked as virtual or as abstract, or be completely implemented.The determination of which method to use is based on the object that makes the call. Inheritance is very useful for adding to the functionality of an existing class without having to reinvent the wheel with each new application.With .NET, you have to remember that you only have single inheritance. A class can implement multiple interfaces, but it must provide the implementation details for all of the interface’s methods. Component programming is probably the way of the future for development. It is a powerful techniquethatenablesyoutoimplementthemultipleinterfacesofanobjecteasily.Thecommongoalofalltheseadvanced object-oriented features is to enable polymorphic programming.

7.9 Casting and Reference ConversionsAn object reference can be:

Implicitly upcast to a base class reference•Explicitly downcast to a subclass reference•

Upcasting and downcasting between compatible reference types performs reference conversions: a new reference is created that points to the same object. An upcast always succeeds; a downcast succeeds only if the object is suitably typed.

7.9.1 UpcastingAn upcast operation creates a base class reference from a subclass reference. For example:Stock msft = new Stock(); // From previous exampleAsset a = msft; // UpcastAfter the upcast, variable a still references the same Stock object as variable msft. The object being referenced is not itself altered or converted:Console.WriteLine (a == msft); // TrueAlthough a and msft refer to the identical object, a has a more restrictive view on that object:Console.WriteLine (a.Name); // OKConsole.WriteLine (a.SharesOwned); // Error

The last line generates a compile-time error because the variable a is of type Asset, even though it refers to an object oftypeStock.TogettoitsSharesOwnedfield,youmustdowncasttheAssettoaStock.

7.9.2 DowncastingA downcast operation creates a subclass reference from a base class reference. For example:Stock msft = new Stock();Asset a = msft; // Upcast

Page 149: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

138

Dot Net Framework (Using C#)

Stock s = (Stock)a; // DowncastConsole.WriteLine (s.SharesOwned); // <No error>Console.WriteLine (s == a); // TrueConsole.WriteLine (s == msft); // TrueAswithanupcast,onlyreferencesareaffected—nottheunderlyingobject.Adowncastrequiresanexplicitcastbecause it can potentially fail at runtime:House h = new House();Asset a = h; // Upcast always succeedsStock s = (Stock)a; // Downcast fails: a is not a StockIf a downcast fails, an InvalidCastException is thrown. This is an example of runtime type checking

7.10 The as operatorThe as operator performs a downcast that evaluates to null (rather than throwing an exception) if the downcast fails:Asset a = new Asset();Stock s = a as Stock; // s is null; no exception thrownThisisusefulwhenyou’regoingtosubsequentlytestwhethertheresultisnull:if (s != null) Console.WriteLine (s.SharesOwned);Theasoperatorcannotperformcustomconversions(see“OperatorOverloading”onpage135)anditcannotdonumeric conversions.

7.11 The is operatorThe is operator tests whether a reference conversion would succeed; in other words, whether an object derives from aspecifiedclass(orimplementsaninterface).Itisoftenusedtotest before downcasting:if (a is Stock) Console.Write (((Stock)a).SharesOwned);The is operator does not consider custom or numeric conversions,butitdoesconsiderunboxingconversions(see“TheobjectType”onpage78).Virtual Function Members

A function marked as virtual can be overridden by subclasses wanting to provide a specialized implementation. Methods, properties, indexers, and events can all be declared virtual:public class Asset{public string Name;public virtual decimal Liability { get { return 0; } }}A subclass overrides a virtual method by applying the overridemodifier:public class House : Asset{public decimal Mortgage;public override decimal Liability{ get { return Mortgage; } }}By default, the Liability of an Asset is 0. A Stock does not need to specialize this behavior. However, the House specializes the Liability property to return the value of the Mortgage:Housemansion=newHouse{Name=”Mansion”,Mortgage=250000 };Asset a = mansion;Console.WriteLine (mansion.Liability); // 250000Console.WriteLine (a.Liability); // 250000

Page 150: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

139

The signatures, return types, and accessibility of the virtual and overridden methods must be identical. An overridden method can call its base class implementation via the base keyword

7.12 Abstract Classes and Abstract MembersA class declared as abstract can never be instantiated. Instead, only its concrete subclasses can be instantiated. Abstractclassesareabletodefineabstractmembers.Abstractmembersarelikevirtualmembers,excepttheydon’tprovide a default implementation. That mplementation must be provided by the subclass, unless that subclass is also declared abstract:public abstract class Asset{// Note empty implementationpublic abstract decimal NetValue { get; }}Subclasses override abstract members just as though they were virtual.

7.13 Hiding Inherited MembersAbaseclassandasubclassmaydefineidenticalmembers.For example:public class A { public int Counter = 1; }public class B : A { public int Counter = 2; }

TheCounterfieldinclassBissaidtohidetheCounterfieldinclassA.Usually,thishappensbyaccident,whenamember is added to the base type after an identical member was added to the subtype. For this reason, the compiler generates a warning and then resolves the ambiguity as follows:

References to A (at compile time) bind to A.Counter.•References to B (at compile time) bind to B.Counter.•

Occasionally,youwanttohideamemberdeliberately,inwhichcaseyoucanapplythenewmodifiertothememberinthesubclass.Thenewmodifierdoesnothingmorethansuppressthecompilerwarningthatwouldotherwiseresult:

public class A { public int Counter = 1; }public class B : A { public new int Counter = 2; }

Thenewmodifiercommunicatesyourintenttothecompiler—andotherprogrammers—thattheduplicatememberis not an accident.

7.14 Sealing Functions and ClassesAn overridden function member may seal its implementation with the sealed keyword to prevent it from being overridden by further subclasses. In our earlier virtual function member example, we could have sealed House’s implementation of Liability, preventing a class that derives from House from overriding Liability, as follows:

public sealed override decimal Liability { get { ... } }Youcanalsosealtheclassitself,implicitlysealingallthevirtualfunctions,byapplyingthesealedmodifiertotheclass itself.

7.15 The base KeywordThe base keyword is similar to the this keyword. It serves two essential purposes: accessing an overridden function member from the subclass, and calling a base class constructor (see next section).

In this example, House uses the base keyword to access Asset’s implementation of Liability:public class House : Asset

Page 151: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

140

Dot Net Framework (Using C#)

{...Inheritancepublic override decimal Liability{get { return base.Liability + Mortgage; }}}

With the base keyword, we access Asset’s Liability property nonvirtually. This means we will always access Asset’s version of this property—regardless of the instance’s actual runtime type. The same approach works if Liability is hidden rather than overridden. (You can also access hidden members by casting to the base class before invoking the function.)

7.16 Constructors and InheritanceAsubclassmustdeclareitsownconstructors.Forexample,ifwedefineBaseclassandSubclassasfollows:

public class Baseclass{public int X;public Baseclass () { }public Baseclass (int x) { this.X = x; }}public class Subclass : Baseclass { }

The following line will give an error:Subclass s = new Subclass (123);

Subclassmust “redefine” any constructors itwants to expose. In doing so, it can call anyof the base class’sconstructors with the base keyword:public class Subclass : Baseclass{public Subclass (int x) : base (x) { ... }}

The base keyword works rather like the this keyword, except that it calls a constructor in the base class. Base class constructorsalwaysexecutefirst;thisensuresthatbaseinitializationoccursbeforespecializedinitialization.Ifaconstructor in a subclass omits the base keyword, the base type’s parameterless constructor is implicitly called (if the base class has no parameterless constructor, the compiler generates an error).

7.17 Constructor and Field Initialization OrderWhen an object is instantiated, initialization takes place in the following order:

From subclass to base class•Fields are initialized. �Arguments to base-class constructor calls are evaluated. �

From base class to subclass•Constructor bodies execute. �

Page 152: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

141

7.18 Overloading and ResolutionInheritance has an interesting impact on method overloading. Consider the following two overloads:

static void Foo (Asset a) { }static void Foo (House h) { }

Whenanoverloadiscalled,themostspecifictypehasprecedence:House h = new House (...);Foo(h); // Calls Foo(House)

The particular overload to call is determined statically (at compile time) rather than at runtime. The following code calls

Foo(Asset), even though the runtime type of a is House:Asset a = new House (...);Foo(a); // Calls Foo(Asset)

InheritanceThe object Type inheritance ‘object (System.Object)’ is the ultimate base class for all types. Any type can be implicitly upcast to object. To illustrate how this is useful, consider a general-purpose stack. A stack is a data structure based ontheprincipleofLIFO—“LastIn,FirstOut.”Astackhastwooperations:pushanobjectonthestack,andpopanobject off the stack. Here is a simple implementation that can hold up to 10 objects:

public class Stack{int position;object[] data = new object[10];public void Push (object o) { data[position++] = o; }public object Pop() { return data[--position]; }}

Because Stack works with the object type, we can Push and Pop instances of any type to and from the Stack:

Stack stack = new Stack();stack.Push(“sausage”);string s = (string) stack.Pop(); // DowncastConsole.WriteLine (s); // sausage

Object is a reference type, by virtue of being a class. Despite this, value types, such as int, can also be cast to and from object. To make this possible, the CLR must perform some special work to bridge the underlying differences between value and reference types. This process is called boxing and unboxing

Page 153: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

142

Dot Net Framework (Using C#)

Summary

Mostmodernlanguages,includingC#,allowtoaddanabstractmodifiertoclassesthatprohibitsotherclasses•from instantiating objects of a base class.The override keyword allows a method to provide a new implementation of a method inherited from a base •class.When we override a method, the signature of the methods must match.•An abstract class may contain one or more abstract methods. Abstract methods are only permitted in abstract •classes.The declaration for an abstract method ends with a semicolon following the signature.•Sealedclassesareusedtorestricttheinheritancefeatureofobjectorientedprogramming.Onceaclassisdefined•as sealed class, this class cannot be inherited. The main purpose of a sealed class is to take away the inheritance feature from the user so they cannot derive •a class from a sealed class.Inheritance, encapsulation and polymorphism, is one of the three primary characteristics or pillars of object-•oriented programming.The class whose members are inherited is called the base class, and the class that inherits those members is •called the derived class.Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and •inheritance.Multiple inheritance is a feature of some object-oriented computer programming languages in which a class •can inherit behaviours and features from more than one super class.When a single derived class is created from a single base class then the inheritance is called as single •inheritance.When more than one derived class are created from a single base class, then that inheritance is called as •hierarchical inheritance.When a derived class is created from another derived class, then that inheritance is called as multi level •inheritance.Any combination of single, hierarchical and multi level inheritances is called as hybrid inheritance.•When a derived class is created from more than one base class then that inheritance is called as multiple •inheritance.Encapsulation is one of the fundamental principles of object-oriented programming, it is a process of hiding all •the internal details of an object from the outside world.A class declared as abstract can never be instantiated.•

Page 154: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

143

ReferencesWorner, M., 2004. • Applied C# in Financial Markets, John Wiley & Sons, Publication.Lippman, S. B., • C# primer A Practicle approach, Pearson Education.The Java Tutorials, • Abstract Methods and classes, [Online] Available at: <http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html> [Accessed 2 February 2012].Sivakumar, N., 2001. • Introduction to inheritance, polymorphism in C# [Online] Available at: <http://www.codeproject.com/Articles/1445/Introduction-to-inheritance-polymorphism-in-C> [Accessed 2 February 2012].ProgrammingVideos, 2010. • C# Tutorial - 12 - Inheritance, Part1 [Video Online] Available at: <http://www.youtube.com/watch?v=_OpWFzhn8VE> [Accessed 6 February 2012].Deccansoft123, 2011. • Interface and Polymorphism in C#, [Video Online] Available at: <http://www.youtube.com/watch?v=2XexwF1TDjo> [Accessed 6 February 2012].

Recommended ReadingLowy, J., July 2005. • Programming .NET components, 2nd edition, O’really Publication.Smyth, N., 2010. • C# Essentials-Version 1.01. Schildt, H., 2009. • The Complete reference C# 3.0, Tata McGraw Hill.

Page 155: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

144

Dot Net Framework (Using C#)

Self Assessment

A class declared as __________ can never be instantiated.1. Sealed a. Protectedb. Abstractc. Private d.

Which class can not be use as a base class?2. Sealeda. Abstractb. Inheritedc. Base classd.

Sealed classes are used to restrict the __________ feature of object oriented programming.3. Inheritancea. Encapsulationb. Castingc. upcastingd.

____________ is the ability for classes to provide different implementations of methods that are called by the 4. same name.

Inheritancea. Encapsulationb. Initialisationc. Polymorphismd.

___________ is a process of hiding all the internal details of an object from the outside world.5. Polymorphisma. Encapsulationb. Sealingc. Inheritanced.

When a single derived class is created from a single base class then the ________ is called as multiple 6. inheritance.

Single inheritancea. Inheritanceb. Hierarchical c. encapsulationd.

Which of the nfollowing statements is true?7. Overriding a method is same as overloading a method.a. Overriding a method is different from overloading a method.b. Overriding a method and overloading a method have different signature.c. Overriding a method or overloading a method may or may not have same signature..d.

Page 156: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

145

Which keyword serves the purpose of sealed class?8. Protecteda. Privateb. NotInheritable c. Publicd.

Onceaclassisdefinedassealedclass,thisclasscannotbe__________.9. Inheriteda. Usedb. Editedc. Declaredd.

Which of the following statements is true?10. A sealed class cannot be an abstract class.a. A sealed class can be an abstract class.b. Any class can be an abstract classc. Abstract class can be a sealed class.d.

Page 157: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

146

Dot Net Framework (Using C#)

Chapter VIII

Managing Console I/O Operations

Aim

The aim of this chapter is to:

introduce the console class•

elucidate error handling and management•

explain various formatting methods•

Objectives

The objectives of this chapter are to:

explain handling different exception types•

explain syntax and nesting of basic try catch block•

analyse the program execution by using breakpoints •

Learning outcome

At the end of this chapter, you will be able to:

identify the run time behaviour of our program•

write programs using ReadLine() and WriteLine() method•

understand the handling of exceptions in the program•

Page 158: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

147

8.1 IntroductionIt is very much essential that we should know how to provide input data and how to present the results in a desired format. For this purpose programs are written to manipulate a given set of data and to generate processed data as output. The same input-process-output cycle is followed every time. We have already seen the use of the Console.WriteLine( ) method to produce simple outputs and Console.Readine( ) method for reading input from the keyboard. In this, chapter, we shall consider in more detail the console I/O operations supported by C#.

8.2 The Console Class The methods for reading from and writing to the console are provided by the System.Console class. This class gives us access to the standard output and standard error streams as shown in table below:

Stream Object RepresentsConsole.In Standard input

Console.Out Standard outputConsole.Error Standard error

Table 8.1 Input/output stream

The standard input system Console.In gets input by default from the keyboard. We can also forward it to receive inputfromafile.ThestandardoutputstreamConsole.Outsendsoutputtothescreenbydefault.Wecanalsosendontheoutputtoafile.ThestandarderrorstreamConsole.Errorusuallysendserrormessagestothescreen.Ifthestandardoutputissenttoafileandifthereareerrormessagespresentthenalsoitwillbedisplayedonthescreen.

8.3 Console InputThe console input stream object supports two methods for obtaining input from the keyboard:

Read( ) -Returns a single character as int. Returns -1 if no more characters are available.•ReadLine( )- Returns a string containing a line of text. Returns null if no more lines are available.•

These methods can be invoked using either Console. In object or Console class itself. The following code reads a character from the keyboard and displays it on the screen.

int x = Console.Read ( );Console.WriteLine ( (char) ):

We have used a casting operator (char) to x to convert it to a character type. Here, x is read as an int. The following code reads entire line of text as a single string and displays it on the screen.

string str = Console.ReadLine ( );Console.WriteLine(str);

To understand the ReadLine method and to read interactivity strings from the keyboard and to echo them to the screen, consider the following example:

Using ReadLine( ) to read stringsusing System;class ReadString{ public static void Main ( ) { Console.WriteLine(“WhatisyourName?”);

Page 159: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

148

Dot Net Framework (Using C#)

string s; s = Console.Readline ( ); Console.WriteLine(“HowareyouMr.”+s); }}

8.4 Console OutputFor writing to the console the console output stream supports two methods:

Write( )- Outputs one or more values to the screen without a newline character.•WriteLine( )- Outputs one or more values to the screen (same as Write () method) but adds a newline character •at the end of the output.

Theabovemethodshavevariousoverloadedformsforhandlingall thepredefined types.Wecaneasilyoutputmany different types of data from it. WriteLine( ) also allows us to output data in many different formats, in a way, comparable to the printf method of C.

TheWrite()methodsendsinformationintoabuffer.Thisbufferisnotflusheduntilanewline(orend-of-line)characteris sent. As a result, this method prints output on one line until a newline character is encountered. For example,

Console.Write(“Hello”);Console.Write(“CSharp!”);

These two statements, will display the words Hello C Sharp! On one line and wait for displaying of further information on the same line. We may force the display to be brought to the next line by printing a newline character as shown below:

Console.Write(“\n”);

For example, Console.Write(“Hello”);Console.Write(“\n”);Console.Write(“CSharp!”);

The above statements will display the output in two lines as follows:HelloC Sharp!

Instead of Write() the WriteLine( ) method takes the information provided and displays it on a single line followed by a line given.

For example:Console.Writeline(“Hello”);Console.Write(“CSharp!”);

The above statements will produce the output as:

Hello C Sharp!

And if the statement Console.WriteLine( ); is written, it will print a blank line as output.

Page 160: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

149

8.5 Formatted OutputBy using the overload WriteLine( ) method we can produce formatted output. This method takes a string containing a format and a list of variables whose values have to be printed out.

The general form of formatted WriteLine( ) method is:Console.WriteLine(format-string, v1, v2,....);

Format string contains both static text and markers which indicate:Where the values are to be printed.•How the values are to be formatted. •

A marker is an index number written in curly brackets, that indicates which variable of the argument list is to be substituted.

Examples: Console.WriteLine(“Totalis{0}”,total); Console.WriteLine(“Sumof{0}and{1}is{2}”,a,b,c);

Intheaboveexamples,{0}representsthefirstargumentinthelist,{1}representsthesecond,andsoon.Forinstance,if a = 100, b = 200 and c = a + b, then the second statement will display the following output: Sum of 100 and 200 is 300 ↑ ↑ ↑ {0} {0} {0} ↑ ↑ ↑ a b c

We can also specify a width for the value using the format:{n,w}

Here,nistheindexnumberandwisthewidthforthevalue.Ifwispositive,thevaluewillbeprintedright-justifiedinthewidth,and,ifitisnegative,thevaluewillbeleft-justified.

Example: int a = 45; int b = 976; int c = a+b;

Console.WriteLine(“{0,5}\n+{1,5}\n-------\n{2,5}”,a,b,c);

This will display the following output: 45 +976 ----------- 1021

Some points to be remember here are:OneWriteLine()statementprintsfourlinesofoutput.Thisisduetouseoflinecharacter‘\n’intheformat•string.We can also print an array of objects using markers in a format string.•

Page 161: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

150

Dot Net Framework (Using C#)

Exampleobject[]array={“abc”,12.3,100,“123”};

Console.WriteLine(“Array:{0},{1},{2},{3}”,array);

To understand how a format string is implemented for displaying a simple formatted output study the following program.

Using format stringsusing System;class FormatString{ public static void Main( ){ Strings=“Items”; int a = 100; floatx=99.9F; Console.WriteLine(“{0}\nIntValue:{1}\nFloatValue:{2}”,s,a,x);}} The output of program would be:Items IntValue: 100FloatValue: 99.9

8.6 Numeric FormattingAsimpleformatstringcanbeusedtooutputdifferenttypesofvalueswiththehelpofmarkers“{}”.Eachmarkercan optionally contain various format characters to specify the nature of numeric format. Marker is also known as placeholder. C# supports two methods of numeric format:

Standard format•Custom format•

Themostcommonlyusedoneisthestandardformatthatconvertsanumerictypetoaspecificstringrepresentation.Wemayusecustomformatiffurtherrefinementoftheoutputformatisrequired.

8.6.1 Standard Numeric FormatThestandardnumericformatconsistsofanumericformatcharacter;italsoconsistsofprecisionspecifierbutitisoptional. The general format of a marker would appear like this:{n:fc[p]}

Wherenistheindexnumberoftheargumenttobesubstituted,fcistheformatcharacterandpistheprecisionspecifier.Following table shows the list of format characters that can be used for formatting the output of numbers.

Page 162: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

151

Format Character Description

C or c Currencyformatting.Bydefault,thedollarsign$willbefixedtothevalue.Aprecisionspecifiermaybeusedtospecifythenumberofdecimalplaces.

D or d Formatintegernumbers,andconvertsintegerstobase10.Aprecisionspecifiermaybeused to pad with leading zeros, if necessary.

Table 8.2 C# Format characters

8.6.2 Custom Numeric FormatC# supports custom format string to provide more control over the output format, if desired. In most of the situations the standard numeric format is good. Here, special characters are used to perform a ‘template’ that decides the nature of output. The commonly used special characters include:

Zero (0)•Pound Character (#)•Period (.)•Comma (,)•Percent Character (%)•

The zero and pound characters are called placeholders.

8.7 Managing Errors and Exceptions Mistakes happen while developing as well as typing a program. It is very rare that a program runs successfully in theveryfirstattempt.Suchmanualmistakesleadtoanerrorcausingtheprogramtoproduceunexpectedresults.Errors are nothing but mistakes that can make a program go wrong.

An error may produce an incorrect output or may terminate the execution of the program unexpectedly or sometimes it causes system to crash. It is therefore important to delete and manage properly all the possible errors and error conditions in the program so that they do not terminate or cause the system to crash during execution. Visual Studio has various tools to overcome the errors for the success of our program such as the Debugger. It can be used to observe the run-time environment and locate logical errors.Using the Debugger, we can stop program execution and check the values stored in memory. We can explore how the Debugger enables to take an up-close look at the code.

Aspecialtypeoferrorcalledanexceptionisunexpectedconditionthatoccursinfrequently.Theyareusuallyassociatedwith error conditions or unexpected behaviours that cause abnormal terminations if they are not handled.

8.8 Types of ErrorsErrorsmaybebroadlyclassifiedintotwocategories:

Compile-time error •Run-time error•

8.8.1 Compile-Time Errors C# compiler detects and displays all syntax errors therefore these errors are known as Compile-time errors. Whenever thecompilerdisplaysanerror,itwillnotcreatethe.csfile.Itisthereforenecessarythatwefixalltheerrorsbeforewe can successfully compile and run the program.

Page 163: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

152

Dot Net Framework (Using C#)

Illustration of compile time error

/* this program contains an error */using System;class Error1{ public static void Main( ) { Console.WriteLine(“HelloC#!”); }}

The C# compiler has made it very easy for users to check and correct the errors. It tells us where the errors are in the program. For example, if we have misspelled the System namespace in the above program, the following message will be displayed on the screen:

Error1.cs (2.7): error cs0234: The type or namespace name ‘System’ does not exists in the class or namespace.

We can go to the appropriate line, correct the error, and recompile the program. Sometimes a single error may be the source of multiple errors later in the compilation. For example, use of an undeclared variable in a number of places willcauseaseriesoferrorsoftype‘undefinedvariable’.Weshouldgenerallyconsidertheearliesterrorsasthemajorsourceofourproblem.Afterwefixsuchanerror,wehaveanopportunitytorecompiletheprogramandlookforothererrors.Mostofthecompile-timeerrorsareduetotypingmistakes.Typographicalerrorsarehardtofind.We may have to check the code word by word, or even character by character. The most common problems are:

Missing semicolons.•Missing (or mismatch of) brackets in classes and methods. •Misspellingofidentifiersandkeywords.•Missingdoublequotesinstrings.•Use of undeclared variables.•Incompatible types in assignment/ initialization.•Bad references to objects.•Use of = in place of == operator. Etc.•

8.8.2 Run-Time ErrorsThe Visual Studio integrated development environment (IDE) reports errors in the program.As discussed earlier there are two types of errors. Compiler errors are the easiest to discover and eliminate.

A compiler error is associated with various language rule:C# has about 90 keywords.• It uses a curly brace notation.•Itrequiresthatstatementsendwithasemicolon.•

C#follows thesophisticated languagerulesknownasC#LanguageSpecifications,whichare theauthoritativesourceforC#grammarandsyntax.Thespecificationsdetailinformationonallaspectsofthelanguage.Aslongasyou do not violate any rules, no syntax errors are issued.

Page 164: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

153

Fig. 8.1 Error list window

IfanerroroccursVisualStudio.NetshowstheErrorListWindowasshowninfigureabove.Ifwemovethecursorover the problem area, a yellow pop-up box called the Quick Info window displays information about the error. Sometimes, the message does not state exactly what the problem is. Sometimes we have to look beyond what the error message states.

8.9 Debugging in C#An application is developed during the design and also when the code is implemented. It is extremely important to desk check the solutions to make sure the program is producing consistently accurate results. To observe the run time behaviour of our program, Visual Studio has provided with a special facility known as Debugger.

Debugger has the various characteristics as follows:It observes the run-time behaviour of our program.•It helps to locate logical errors.•The Debugger allows breaking or halting the execution of the program to examine the code.•Evaluates variables in the program.•It helps to view the memory space used by our application. •We can step through an application, checking the values of variables as each line is executed. •Visual Studio also allows setting breakpoints in our program code. •A breakpoint is a line in our program that we select and when it is reached, the program is suspended or placed •in break mode. While in break mode, we have an opportunity to examine, and even change, the value of variables. The Visual Studio Debugger provides a Debug menu with access to the Debugger tools.•

8.10 Execution ControlThe Debugger provides commands for controlling the execution of our application. With the help of Debugger, we canstartorcontinueexecution,breakexecution,stepthroughanapplication,orruntoaspecificpointintheprogram.We can examine the code while it is running to validate that the execution path is what we had planned.

Follow the procedure below to debug the program. Select the Debug menu - selected Start Without Debugging or Start Debugging or used their shortcuts (Ctrl+F5 or F5). As shown infigurebelowtheDebugmenuoffersadditionalchoices.

Page 165: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

154

Dot Net Framework (Using C#)

Fig. 8.2 Debug menu options

If we select the Start Debugging option to run the program, the Debug menu changes. The number of options available almost doubles. Figure 8.3 shows the options available when a program is running. Several of the options refer to a breakpoint.

Fig. 8.3 Debug menu options during debugging mode

8.11 BreakpointsBreakpoints are the markers that are placed in an application. It indicates that the program should halt execution when it reaches breakpoint. When the break occurs, the program and the Debugger are said to be in break mode. In that break mode, we can examine expressions, check the values that are being generated, also it allows check intermediate values in the program if our program is not consistently producing correct results. Various methods can be use to add or set a breakpoint. The simplest method is to click anywhere on a line of executable code where we want to set a breakpoint and select Toggle Breakpoint from the Debug menu or use the F9 keyboard shortcut. As the menu option name implies, pressing F9, or selecting Toggle Breakpoint a second time turns off the breakpoint. Another approach for setting the breakpoint involves positioning the mouse in the gray area to the left of the line of executable code, where you want to set a breakpoint, and then clicking the left mouse button. A red breakpoint glyph is placed on the line where the breakpoint is set.

Page 166: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

155

Followingfigurewillhelptounderstandtheprocess.

Fig. 8.4 Breakpoint set

The line of code is also automatically selected. We can place any number of breakpoints in our program following these methods.

If we are in debugging mode then to see the Locals window use the Windows option from the Debug menu to display the window. Following window will appear after debugging known as the local window at breakpoint. Figure below shows the local window at breakpoints:

Fig. 8.5 Locals window at the breakpoint

This application was developed to improve the execution speed. The user was asked to input the speed limit, the speedtheyweretravellingandthestudent’sclassification.Abreakpointwassetonthelinethatcalculatedthespeedfine.Priortothebreakpoint,intheconstructoroftheTicketclass,thespeedforthefinewascalculated.Asgivenin the Locals window given above, we can see the values for speed, speed Limit, and class if. At that breakpoint, Fineandfinevalueshavenotbeenset.Wecanalsoseethatexecutionhaltsbeforetheprogramstatementsonthatline being executed.

Page 167: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

156

Dot Net Framework (Using C#)

OncewefinishreviewingthevariablesandexpressionsbypressingF5orselectingContinuefromthedebugmenu.It takes the program out of break mode and restores it to a run-time mode. If only one breakpoint is set, the Locals window closes and the execution continues until the end of the Main( ) method is reached. At that point, the program terminates. However, if more than one breakpoint is set, selecting Continue causes the program to execute from the halted line until it reaches the second breakpoint. At that point, the Locals window is updated and the program is again paused. To illustrate the changes made to the Locals window, a second breakpoint was set on the last line in theSetFine()methodoftheTicketclass.AsshowninFigure8.6,thefinevariableandFinepropertywerechangedfrom 0 to 712.5.The Debugger uses an arrow to point to the line where the program halts. The process of stopping at each breakpoint would continue until the end of the program was encountered.

Fig. 8.6 Local window after debugging

8.12 Exceptions Syntax of Exception Handling CodeFollowing is the mechanism of C# exception handling

The basic try/catch blockThe try/catch block is the primary mechanism of C# exception handling. This permits separation of error handling fromthenormalflowofanalgorithm.Essentially,thealgorithmismoreunderstandablebecauseitsactionsrelateprimarily toward the goal of a method, rather than with the complex mixture of error handling.

Syntax for the basic try/catch block is as follows:try

{// some algorithm}catch (Exception e){// exception handling code}

The try portion of the try/catch block holding statements could potentially result in an exception being raised. If an exception is raised, it could be handled in the catch portion of the try/catch block. The catch block is where exceptionsarehandled.Thecatchblockshavefilterthatdefineswhattypeofexceptiontheycanhandle.Alatersection of this chapter discusses exception objects, how to handle more than one, and how to choose which exception object type to use.

Code given below is written in try block. It will cause an error, the error condition and an exception will be raised, The catch block will handle that exception.

Page 168: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

157

A Simple Exception: Exceptions.csusing System;public class Exceptions{public static int Main(string[] args){byte[] myStream = new byte[3];try{for (byte b=0; b < 10; b++){Console.WriteLine(“Byte{0}:{1}”,b+1,b);myStream[b] = b;}}catch (Exception e){Console.WriteLine(“{0}”,e.Message);}return 0;}}

Output:Byte 1: 0Byte 2: 1Byte 3: 2Byte 4: 3

Index was outside the bounds of the array. This example shows a try/catch block in action. Before the try block the program declares a three-element array of bytes named myStream. Within the try block, there is a for loop, set to add 10 bytes to the myStream array. It prints out the byte number and then the value. Then it assigns the byte value to the myStream array.

This works well until the fourth iteration of the for loop. Because the myStream array can hold only 3 bytes, trying to add a fourth is an error. This generates an exception, causing program control to jump into the catch block.

8.13 Handling ExceptionsAlthoughsettinguptry/catch/finallyblocksandcatchingthegenericexceptionisbetterthannotcatchingerrorsat all, there are various methods of handling errors to make code more robust. This section shows how to handle errors in a few of different ways, including handling multiple exception types, handling and passing on exceptions, and recovering from exceptions.

Handling different exception typesWe have already learnt how to catch the generic exception, System.Exception, but that was for demonstration purposes and isn’t appropriate for most situations. In most cases, we will see an exception derived from System.Exceptionthatismorespecificforourneeds.Wecanevendefinemultiplecatchblocksfortheexceptiontypesyouwant to handle.

Thisworksbyplacingadditionalcatchblocksbelowthetryblock.Ourcatchblocksshouldbeorderedbyspecificityof the exception they handle. Failure to do so results in a compiler error. Program with multiple catch blocks is written as follows.

Page 169: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

158

Dot Net Framework (Using C#)

Multiple catch Blocks: Exceptions3.csusing System;using System.IO;public class Exceptions3{public static int Main(string[] args){int mySize = 3;byte[] myStream = new byte[mySize];int iterations = 5;StreamWritersw=newStreamWriter(“exceptions.txt”);try{for (byte b=0; b < iterations; b++){sw.WriteLine(“Byte{0}:{1}”,b+1,b);myStream[b] = b;}}catch (IndexOutOfRangeException iore){Console.WriteLine(“IndexOutofRangeException:{0}”,iore.Message);}catch (Exception e){Console.WriteLine(“Exception:{0}”,e.Message);}Finallysw.WriteLine(“Close”);sw.Close();}return 0;}}

The example shows two catch blocks. The catch block with the IndexOutOfRangeExceptionhandlerismorespecificthanthecatchblockwiththeExceptionhandler.Therefore,whenthisprogramexecutes,anexception is generated that invokes the catch block for the IndexOutOfRangeException. Had the error been another type of exception, the catch block for the Exception handler would have been executed.

8.14 Multiple Catch StatementIt is possible to have more catch statement in the catch block as illustrated below:............................try{ statement; // generates an exception}Catch (Exception-Type-1 e){

Page 170: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

159

statement ; // processes exception type 1}Catch (Exception-Type-2 e){ statement ; // processes exception type 2}...Catch (Exception-Type-N e){ statement ; // processes exception type N}............................

When an exception in a try block is generated, the C# treats the multiple catch statements like cases in a switch statement.Thefirststatementwhoseparametermatcheswiththeexceptionobjectwillbeexecuted,andtheremainingstatementswillbeskipped.C#doesnotrequireanyprocessingoftheexceptionatall.Wecansimplyhaveacatchstatement with an empty block to avoid program abortion.

Example:catch (Exception e) {}This statement will catch an exception and then ignore it.

Page 171: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

160

Dot Net Framework (Using C#)

Summary

It is very much essential that we should know how to provide input data and how to present the results in a •desired format.The methods for reading from and writing to the console are provided by the System.Console class.•Read( ) returns a single character as int. Returns -1 if no more characters are available.•ReadLine returns a string containing a line of text. Returns null if no more lines are available.•Write( )- outputs one or more values to the screen without a newline character.•WriteLine outputs one or more values to the screen (same as Write () method) but adds a newline character at •the end of the output.By using the overload WriteLine( ) method we can produce formatted output.•C# supports custom format string to provide more control over the output format.•Special characters are used to perform a ‘template’ that decides the nature of output.•Sometimes a single error may be the source of multiple errors later in the compilation.•The Debugger allows breaking or halting the execution of the program to examine the code.•Breakpoints are the markers that are placed in an application.•The try/catch block is the primary mechanism of C# exception handling•The try portion of the try/catch block holding statements could potentially result in an exception being raised.•ThecatchblockwiththeIndexOutOfRangeExceptionhandlerismorespecificthanthecatchblockwiththe•Exception handler.When an exception in a try block is generated, the C# treats the multiple catch statements like cases in a switch •statement.C#doesnotrequireanyprocessingoftheexceptionatall.Wecansimplyhaveacatchstatementwithanempty•block to avoid program abortion.

Page 172: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

161

ReferencesBalagurusamy, E., 2008, • Programming in C#. 2nd ed.,Tata McGraw-Hill.McFarland, J., 2008. • C# 3.0 Unleashed With the .NET Framework 3.5, 2nd ed., Pearson Education.Carr, R., • Breakpoints and Trace points in Visual Studio [Online] Available at: <http://www.blackwasp.co.uk/VSBreakpoints.aspx> [Accessed 30 January 2012].Dot Net Pearls., • C# Console.WriteLine Use [Online] Available at: <http://www.dotnetperls.com/multiple-local-variable> [Accessed 27 December 2012].visitignani, 2011. C# 4.0 - Ch:01 - A - Introduction, [Video Online] Available at: <http://www.youtube.com/•watch?v=cnzWPDxuU0g> [Accessed 3 February 2012].csharpdemos, 2011. C# Tutorial 2 - Console input and Output, [Video Online] Available at: <http://www.youtube.•com/watch?v=3AJ7dRf3rew> [Accessed 3 February 2012].

Recommended ReadingSolis, D., 2008, • Illustrated C# , Springer-Verlag New York.Skeet, J., 2008. • C# in Depth, Manning Publication.Doyle, B., 2008. C# Programming: From Problem Analysis to Program Design, 2nd ed., Thomson •Publication.

Page 173: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

162

Dot Net Framework (Using C#)

Self Assessment

Marker is also known as ________________.1. placepointera. placeholderb. pacemakerc. pointerd.

Which of the following statements is true?2. Breakpoints are the markers that are placed in an application.a. Breakpoints are not placed in an application.b. Markers are placed in an application.c. Break points are not markers.d.

Which of the following statement is true?3. All syntax errors are known as run time error.a. All syntax errors are known as compile time error.b. All errors are of run time errors.c. All errors are of compile time errors.d.

Match the columns.4. Type Output1. Read( ) A. Outputs one or more values to the screen2. ReadLine( ) B. Outputs one or more values to the screen without a newline character3. Write( ) C. Returns a string containing a line of text4. WriteLine( ) D. Returns a single character as int

1-D, 2-C, 3-B, 4-Aa. 1-A, 2-B, 3-C, 4-Db. 1-B, 2-C, 3-B, 4-Dc. 1-B, 2-A, 3-C, 4-Dd.

__________ helps to locate logical errors.5. Debuggera. Compilerb. Constructerc. Copy constructord.

Which of the following statements is true?6. Debugger causes the program to execute from the halted line until it reaches the second breakpoint.a. Breakpoints causes the program to execute from the halted line untill it reaches the second breakpoint.b. Error causes the program to execute from the halted line until it reaches the second breakpoint.c. Constructor causes the program to execute from the halted line until it reaches the second breakpoint.d.

Page 174: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

163

The character ____ is used in currency formatting.7. $a. Fb. Rc. Cd.

The character ____is used to format The integer numbers.8. Da. Ib. Nc. !d.

The general format of a marker would appear like this:9. {f:nc[p]}a. {p:nc[f]}b. {n:fc[p]}c. {c:pc[n]}d.

__________outputs one or more values to the screen but adds a newline character at the end of the output.10. Write ()a. ReadLine()b. WriteLine()c. CommandLine()d.

Page 175: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

164

Dot Net Framework (Using C#)

Application I

C# code for how to create bounced mail handle using .Net 4.0private void button1_Click(object sender, System.EventArgs e){// The Chilkat Bounce component is used to classify an email as// one of several types of automated replies such as bounced//emailmessages,viruswarnings,out-of-officereplies,etc.// To read email from a POP3 server, the Chilkat Mail component// (licensed separately) is used.Chilkat.MailMan mailman = new Chilkat.MailMan();mailman.UnlockComponent(“MailUnlockCode”);mailman.MailHost=“mail.chilkatsoft.com”;mailman.PopUsername=“login”;mailman.PopPassword=“password”;Chilkat.Bounce bounce = new Chilkat.Bounce();boolsuccess=bounce.UnlockComponent(“BounceUnlockCode”);if (!success){textBox1.Text = bounce.LastErrorText;return;}// Read email from the POP3 server.Chilkat.EmailBundle bundle;bundle = mailman.CopyMail();if (bundle != null) {// Loop over each email...Chilkat.Email email;int i;bool success;for (i=0; i<bundle.MessageCount; i++){email = bundle.GetEmail(i);// See if this is a bounced email.// This sets the properties of the Bounce objectsuccess = bounce.ExamineEmail(email);if (!success)listBox1.Items.Add(“Failedtoclassifyemail”);else if (bounce.BounceType == 1) // Hard bounce, log the email addresslistBox1.Items.Add(“HardBounce:“+bounce.BounceAddress);else if (bounce.BounceType == 2) // Soft bounce, log the email addresslistBox1.Items.Add(“SoftBounce:“+bounce.BounceAddress);else if (bounce.BounceType == 3) // General bounce, no email address available.listBox1.Items.Add(“GeneralBounce:Noemailaddress”);else if (bounce.BounceType == 4) // General bounce, log the email addresslistBox1.Items.Add(“GeneralBounce:“+bounce.BounceAddress);else if (bounce.BounceType == 5) // Mail blocked, log the email address

Page 176: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

165

listBox1.Items.Add(“MailBlocked:“+bounce.BounceAddress);else if (bounce.BounceType == 6) // Auto-reply, log the email addresslistBox1.Items.Add(“Auto-Reply:“+bounce.BounceAddress);else if (bounce.BounceType == 7) // Transient (recoverable) Failure, log the email addresslistBox1.Items.Add(“TransientFailure:“+bounce.BounceAddress);else if (bounce.BounceType == 8) //Subscriberequest,logtheemailaddresslistBox1.Items.Add(“SubscribeRequest:“+bounce.BounceAddress);else if (bounce.BounceType == 9) //UnsubscribeRequest,logtheemailaddresslistBox1.Items.Add(“UnsubscribeRequest:“+bounce.BounceAddress);else if (bounce.BounceType == 10) //VirusNotification,logtheemailaddresslistBox1.Items.Add(“VirusNotification:“+bounce.BounceAddress);else if (bounce.BounceType == 11) // Suspected bounce.// This should be rare. It indicates that the Bounce// component found strong evidence that this is a bounced//email,butcouldn//tquiterecognizeeverythingit// needed to be 100% sure. Feel free to notify// [email protected] regarding emails having this// bounce type.listBox1.Items.Add(“SuspectedBounce!”);email = null;}bundle = null;}mailman = null;}}(Source: C# Examples [Online] Available at< http://www.example-code.com/csharp/emailObject.asp> [Accessed 6 February 2012].)

Questions

Write a short note on this keyword and give a small program using this.1.

Answer: The this keyword refers to the current instance of the class. Static member functions do not have a this pointer. The this keyword can be used to access members from within constructors, instance methods, and instance accessors.

Programusingthiskeyword:Toqualifymembershiddenbysimilarnames.

public Employee(string name, string alias) { this.name = name; this.alias = alias;}To pass an object as a parameter to other methods, for example:CalcTax(this);To declare indexers, for example:

Page 177: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

166

Dot Net Framework (Using C#)

public int this [int param]{ get { return array[param]; } set { array[param] = value; } }

Explain if and if-else statement.2.

Answer: If :The if statement is a powerful decision-making statement and is used to control theflowofexecution of statements. It is two-way decision statement and is used in conjunction with an expression. It takes the following form.

If (expression)Itallowsthecomputertoevaluatetheexpressionfirstandthen,dependingonwhetherthevalueoftheexpression(relation or condition) is true or false, it transfers the control to a particular statement.

The if statement selects a statement for execution based on the value of a Boolean expression. It takes the following form:

if (expression) statement1[else statement2]where:

expression

An expression that can be implicitly converted to bool or a type that contains overloading of the true and false operatorsstatement1

The embedded statement(s) to be executed if expression is truestatement2

The embedded statement(s) to be executed if expression is false

If-else : The if statement selects a statement for execution based on the value of a Boolean expression. In the following example, the Boolean variable result is set to true and then checked in the if statement. The output is:

The variable is set to true.

bool result = true;

if (result){Console.WriteLine(“Thevariableissettotrue.”);}

Page 178: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

167

else{Console.WriteLine(“Thevariableissettofalse.”);}Iftheexpressionintheparenthesisisevaluatedtobetrue,thentheConsole.WriteLine(“Thevariableissettotrue.”);statement is executed. After executing the if statement, control is transferred to the next statement. The else is not executed in this example.

If you wish to execute more than one statement, multiple statements can be conditionally executed by including them into blocks using {} as in the example above.

The statement(s) to be executed upon testing the condition can be of any kind, including another if statement nested into the original if statement. In nested if statements, the else clause belongs to the last if that does not have a corresponding else. For example:

int x = 12;int y = 18;

if (x > 10) if (y > 20)Console.Write(“Statement_1”); elseConsole.Write(“Statement_2”);

In this example, Statement_2 will be displayed if the condition (y > 20) evaluates to false. However, if you want to associate Statement_2 with the condition (x >10), use braces:

if (x > 10){ if (y > 20)Console.Write(“Statement_1”);}elseConsole.Write(“Statement_2”);

In this case, Statement_2 will be displayed if the condition (x > 10) evaluates to false

What does the // line mean?3.

Answer: The two lines // are called as comment lines in the program. The characters // convert the rest of the line to a comment. For example, // A Hello World! program in C#. In this program the sentense after comment line will not get executed because it is commented. This is generally used for the programmers reference to a perticular line or to stop program to run particular block in the eprogram.

We can also comment out a block of text by enclosing it between the /* and */ characters, for example,/*A“HelloWorld!”programinC#.Thisprogramdisplaysthestring“HelloWorld!”onthescreen.*/

Page 179: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

168

Dot Net Framework (Using C#)

Application II

Program to Convert HTML Text into Plain Text//Any string argument automatically begins the 30-day trial.bool success;success=h2t.UnlockComponent(“30-daytrial”);if (success != true) {MessageBox.Show(h2t.LastErrorText); return;}//Set the HTML:string html;html=“<html><body><p>Thisisatest.</p><blockquote>Hereistextwithinablockquote</blockquote></body></html>”;string plainText;plainText = h2t.ToText(html);textBox1.Text+=plainText+“\r\n”;

(Source: C# Examples [Online] Available at< http://www.example-code.com/csharp/emailObject.asp> [Accessed 6 February 2012].)

Questions

Write a reverse program to convert plain text into HTML text.1. Write a simple program in C# using boolean expression.2. Create a basic HTML page and use C# coding in it using a simple program.3.

Page 180: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

169

Application III

Program to Send a Basic Email in C#// Create a mailman object for sending email.Chilkat.MailMan mailman = new Chilkat.MailMan();// Any string argument automatically begins the 30-day trial.mailman.UnlockComponent(“30-daytrial”);// Set the SMTP server hostname.mailman.SmtpHost=“smtp.earthlink.net”;// Create a simple email.Chilkat.Email email = new Chilkat.Email();email.Body=“Thisisthebody”;email.Subject=“Thisisthesubject”;email.AddTo(“ChilkatSupport”,”[email protected]”);email.From=“JackJohnson<[email protected]>”;// Send mail.bool success;success = mailman.SendEmail(email);if (success){ MessageBox.Show(“Sentmail!”);}else{ MessageBox.Show(mailman.LastErrorText);}

(Source: C# Examples [Online] Available at< http://www.example-code.com/csharp/emailObject.asp> [Accessed 6 February 2012].)

QuestionsCreate a windows application form and write a program to calculate sum of two digits.1. Create a windows application form and write code in it to accept employee details in it.2. Writeaprogramtofindtheenteredprogramisevenorodd?3.

Page 181: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

170

Dot Net Framework (Using C#)

Bibliography

ReferencesBalagurusamy E., 2008. • Programming in C#, Tata McGraw Hill.Bizhostnet. • Microsoft .NET Framework. [Online] Available at: <http://www.bizhostnet.com/pg_frame-net-hosting.html> [Accessed 24 January 2011]Wasp, B., • C# Value Types and Reference Types. [Online] Available at: <http://www.blackwasp.co.uk/ValueReferenceTypes.aspx> [Accessed 27 December 2012].C# • Video Programming Tutorials Episode 1: Gathering The Tools We Need. [Video Online] Available at: <http://www.youtube.com/watch?v=wYP-ruzN8SQ> [Accessed 24 January 2012]Carr, R., • Breakpoints and Trace points in Visual Studio [Online] Available at: <http://www.blackwasp.co.uk/VSBreakpoints.aspx> [Accessed 30 January 2012].Chand, M., 2002, • Working With Arrays in C# .NET [Online], Available at: <http://www.scriptcanal.com/articles_73_Working-with-Arrays-in-C%23--NET.html> [Accessed 31 January 2012].Chromatophore, 2008. • Decision Making and Branching, [Online] Available at: <http://mycblog.org/index.php?option=com_content&view=article&id=47&Itemid=66 > [Accessed 31 January 2012].csharpdemos, 2011. • C# Tutorial 10 - Methods and Return Types, [Video Online] Available at: <http://www.youtube.com/watch?v=9Y1giYg-Zt8> [Accessed 3 February 2012].csharpdemos, 2011. • C# Tutorial 16 - The Foreach Loop, [Video Online] Available at: <http://www.youtube.com/watch?v=ypgRaSsnq7w>[Accessed3February2012].csharpdemos, 2011. C# Tutorial 2 - Console input and Output, [Video Online] Available at: <http://www.youtube.•com/watch?v=3AJ7dRf3rew> [Accessed 3 February 2012].Deccansoft123, 2011. • Interface and Polymorphism in C#, [Video Online] Available at: <http://www.youtube.com/watch?v=2XexwF1TDjo> [Accessed 6 February 2012].Dot Net Pearls., • C# Console.WriteLine Use [Online] Available at: <http://www.dotnetperls.com/multiple-local-variable> [Accessed 27 December 2012].Dot Net Pearls., • C# Multiple Local Variable Declarations [Online] Available at: <http://www.dotnetperls.com/multiple-local-variable> [Accessed 27 December 2012].Dot Net Perls, • C# Operator Overloading. [Online] Available at: <http://www.dotnetperls.com/operator> [Accessed 1 February 2010].Doyle, B., 2011• , C# Programming 3E, Course Technology, Cenage learning.ecturesnippets, 2011. Visual • C# 2010 - Methods Part 1 (Creating a Simple Method), [Video Online] Available at: <http://www.youtube.com/watch?v=rlv7Er3I9oU> [Accessed 3 February 2012].Ed Guzman., 2010. • Delegates in C#- Attempt to Look Inside- Part 3, [Online] Available at: <http://www.codeproject.com/Articles/115710/Delegates-in-C-Attempt-to-Look-Inside-Part-3> [Accessed 1 February 2010].Espinosa, E.D., 2008. • Classes and Objects in C#, Part1 [Video Online] Available at: <http://www.youtube.com/watch?v=ANTE74P5j_w> [Accessed 6 February 2012].Espinosa, E.D., 2008. • Classes and Objects in C#, Part3 [Video Online] Available at: <http://www.youtube.com/watch?v=RlDR-zl5Ook> [Accessed 6 February 2012].Grip, J., 2003. • C# Programming tutorial (1of2). [Video Online] Available at: <http://www.youtube.com/watch?v=NC5s__B6WVQ> [Accessed 24 January 2011]Gunnerson, E., 2001. • A programmer’s introduction to C#, 2nd ed., Apress Publication. Hejlsberg, A., Torgersen, M., Wiltamuth, S. and Golde. P., 2010. • The C# Programming Language, 4th ed., Pearson Education Publication.

Page 182: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

171

Holzner, S., 2003, • Object-Oriented Programming in C#, [Online] Available at: <http://www.informit.com/articles/article.aspx?p=101373> [Accessed 1 February 2012].Jack Xu, 2008. • Practical Numeric Methods with C#, C# Math Application SeriesLippman, S. B., • C# primer A Practicle approach, Pearson Education.Mayo, J., 9 February 2011, • The C# Station Tutorial, [Online] Available at: <http://www.csharp-station.com/Tutorials/Lesson04.aspx> [Accessed 31 January 2012].McFarland, J., 2008. • C# 3.0 Unleashed With the .NET Framework 3.5, 2nd ed., Pearson Education.Michael Y., • Introduction to Objects and Classes in C#, Part 2, [Online] Available at: <http://function.name/articles/Csharp/23 > [Accessed 1February 2012].MillionIT, 2011. • Tutorial 13: C# (C Sharp): foreach loop, [Video Online] Available at: <http://www.youtube.com/watch?v=KDrcj5XiwC0> [Accessed 3 February 2012]. Oberg, R. J., 2002. • C# Using .NET, Prentice Hall PTR Publication.ProgrammingVideos, 2008. • C# Tutorial - 01 - Introduction to C#, [Video Online] Available at: <http://www.youtube.com/watch?v=aJoeeHT8zdA>[Accessed 27 December 2012].ProgrammingVideos, 2010. • C# Tutorial - 12 - Inheritance, Part1 [Video Online] Available at: <http://www.youtube.com/watch?v=_OpWFzhn8VE> [Accessed 6 February 2012].ProgrammingVideos, 2010. • C# Tutorial - 18 - Interface, [Video Online] Available at: <http://www.youtube.com/watch?v=oHKec9XFZdc> [Accessed 3 February 2012].QuackWare, 2011. • Inheritance, Abstract Classes, and Interfaces - C# C Sharp Visual Studio 2010, [Video Online] Available at: <http://www.youtube.com/watch?v=2fyc1QW-FXI&feature=results_main&playnext=1&list=PL0799377C5CCA5299> [Accessed 3 February 2012].Rasheed, F., 2006, • Programmer’s Heaven C# School. Synchron Data publication.Robert, J., 2006, • Introduction to C#, [Online] Available at: <http://zone.ni.com/devzone/cda/ph/p/id/44#toc0> [Accessed 31 January 2012].Sempf, B., Sphar, C., Davis, S. and Sphar, C., 2010. • C# 2010 for Dummies, Wiley Publishing, Inc.shamma1, 2008. • Introduction to C#, [Video Online] Available at: <http://www.youtube.com/watch?v=J95GdnHsn9s> [Accessed 27 December 2012].Sivakumar, N., 2001. • Introduction to inheritance, polymorphism in C# [Online] Available at: <http://www.codeproject.com/Articles/1445/Introduction-to-inheritance-polymorphism-in-C> [Accessed 2 February 2012].Solis D., 2008, • Illustrated C# 2008 C# presented clearly, concisely, and visually, Apress Publiscation.Telles, M. and Kogent solution, 2008. • C# 2005 Programming Black Book, Dreamtech Publication. The Java Tutorials, • Abstract Methods and classes, [Online] Available at: <http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html> [Accessed 2 February 2012].Theazon.com, 2011. • Top 10 most popular programming language. [Online] Available at: <http://theazon.com/2011/10/top-10-most-popular-programming-language/> [Accessed 24 January 2011]visitignani, 2011. C# 4.0 - Ch:01 - A - Introduction, [Video Online] Available at: <http://www.youtube.com/•watch?v=cnzWPDxuU0g> [Accessed 3 February 2012].William, R., 2002. • Pure C# A Code-Intensive Premium Reference, 1st ed., SAMS Publication.Worner, M., 2004. • Applied C# in Financial Markets, John Wiley & Sons, Publication.

Page 183: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

172

Dot Net Framework (Using C#)

Recommended ReadingAlbahari, J. and Albahari, B., • C# 4.0 Pocket Reference, O’really Publication.Bako, P., 2010. • Introduction to C#, Createspsce Publication.Blum, R., 2003, • C# Network Programming, SYBEX san Francisco London.Dixit, J. B., 2005.• Fundamentals of Computing, Laxmi Publications (P) LTD.Doyle, B., 2008. • C# Programming: From Problem Analysis to Program Design, 2nd ed., Thomson Publication. Harvey, M. D. and Paul, J. D., 2006. • C# for Programmers, Pearson Education.Hunt, J., 2002. • Guide to C# And Object Orientation, Springer Publication.James, F., 2003. • Teach Yourself Visual C# >NET 2003, 1st ed., SAMS Publication.Liberty, J. and MacDonald, B., 2008, • Learning C# 3.0, 1st ed., O’really publication.Lowy, J., July 2005. • Programming .NET components, 2nd edition, O’really Publication.Mayo, J., • C# 3.0 Unleased, 2nd ed., SAMS Publication. Michaelis, M., 2009. • Essential C# 3.0 .NET Framework 3.5, 1st ed., Pearson Education.Michelsen, K., 2002. • C# Primer Plus, Sams Publication.Purdum, J., 2008. • C# 3.0 An Introduction to Object Oriented Programming, Wrox Publication.Rama Krishna Rao, B., 2007. • C# Concepts And Practice, Prentice-Hall publication.Sathiaseelan, J. G. R. and Sasikaladevi, N., 2009. • Programming with C# .NET, PHI Publication.Schildt, H., 2009. • The Complete reference C# 3.0, Tata McGraw Hill.Schildt, H., 2010. • The Complete Reference C# reference 4.0, 2nd ed., Tata McGRaw Hill.Skeet, J., 2008. • C# in Depth, Manning Publication.Smyth, N., 2010. • C# Essentials-Version 1.01. Solis, D., 2008, • Illustrated C# , Springer-Verlag New York.Stellman, A. and Green, J., • Head First C#, O’really Publication.Steven, J. M., 2009. • Design Patterns in C#, Pearson Education.Watson, B., 2010. • C# 4.0 How-To, Pearson Education.

Page 184: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

173

Self Assessment Answers

Chapter Ia1. d2. a3. d4. c5. c6. a7. b8. b9. a10.

Chapter IId1. b2. a3. d4. c5. a6. a7. c8. c9. d10.

Chapter III

c1. b2. a3. c4. d5. b6. c7. a8. a9. d10.

Chapter IVa1. a2. d3. a4. d5. b6. a7. a8. c9. d10.

Page 185: Dot Net Framework (Using C#)jnujprdistance.com/assets/lms/LMS JNU/MCA/Sem III... · Dot Net Framework (Using C#) Board of Studies Prof. H. N. Verma Prof. M. K. Ghadoliya Vice- Chancellor

174

Dot Net Framework (Using C#)

Chapter Va1. a2. a3. c4. b5. c6. a7. b8. d9. a10.

Chapter VIa1. d2. d3. a4. a5. b6. c7. a8. b9. a10.

Chapter VIIc1. a2. a3. d4. b5. b6. b7. c8. a9. a10.

Chapter VIIIb1. a2. b3. a4. a5. b6. d7. a8. c9. c10.