Vous êtes sur la page 1sur 79

Programming Using C# – I_SG/12-M06-V01

This product or document is protected by copyright and Copyright ©NIIT. All rights reserved.
distributed under licenses restricting its use, copying,
distribution and decompilation. Please view “Mark of
Authenticity” label to establish proper licensed usage.
No part of this document may be copied, reproduced,
printed, distributed, modified, removed, amended in any
form by any means whether electronic, mechanical,
digital, optical, photographic or otherwise without prior
written authorization of NIIT and its authorized
licensors, if any.

Information in this document is subject to change by


NIIT without notice. The names of companies, products,
people, characters, and/or data mentioned herein are
fictitious and are in no way intended to represent any
real individual, company, entity, services, product or
event, unless otherwise noted.

All products are registered trademarks of their respective


organizations.
All software is used for educational purposes only.

Disclaimer: The documents and graphics on this


courseware could include technical inaccuracies or
typographical errors/translation errors. Changes are
periodically added to the information herein. NIIT may
make improvements and/or changes herein at any time.
NIIT makes no representations about the accuracy of the
information contained in the courseware and graphics in
this courseware for any purpose. All documents and
graphics are provided "as is". NIIT hereby disclaims all
warranties and conditions with regard to this
information, including all implied warranties and
conditions of merchantability, fitness for any particular
purpose, title and non-infringement. In any event, NIIT
and/or its licensor(s)/supplier(s) shall not be liable to any
party for any direct, indirect, special or other
consequential damages for any use of the courseware/
translated courseware, the information, or on any other
hyper linked web site, including, without limitation, any
lost profits, business interruption, loss of programs or
other data on your information handling system or
otherwise, even if NIIT is expressly advised of the
possibility of such damages.

Due to the dynamic nature of the internet, the URLs and


web references mentioned in this document may be (are)
subject to changes, for which NIIT shall not hold any
responsibility.
 Basic knowledge about the various parts of the
computer and should know the basic difference
between hardware and software.
About This Course  Knowledge of programming logic and
techniques.
 The ability to build flowcharts and write
Prologue algorithms to solve problems.
 Basic knowledge of object-oriented concepts.

Description Exit Profile


This course introduces you to object-oriented After completing this course, the student should be able
methodology using C# as the programming language. It to:
introduces the implementation of object-oriented  Develop object-oriented console applications
concepts, such as abstraction, encapsulation, using C#.
polymorphism, and inheritance, using C#. In addition,
this course introduces implementation of various
programming concepts, such as threads, file handling, Conventions
and delegates used in C#.

Rationale Convention Indicates...


Note
Object-oriented concepts form the base of all modern
programming languages. Understanding the basic
concepts of object-orientation helps a developer to use Hint
various modern day programming languages, more
effectively. C# (C Sharp) is an object-oriented
programming language developed by Microsoft that
intends to be a simple, modern, and general-purpose Animation
programming language for application development.
The course is applicable to students who want to enter
Just a Minute
the world of object-oriented programming, using the C#
language. This course provides a strong foundation in
object-oriented programming approaches and the Streaming Media
fundamentals of C# programming language.

Let’s Practice
Objectives
After completing this course, the student should be able
to:
 Identify the basics of the C# language
 Work with operators and programming
constructs
 Work with class members
 Create value types and reference types
 Extend existing classes using inheritance
 Implement polymorphism
 Implement file input and output operations
 Handle expections
 Create multithreaded applications
 Work with delegates and events
 Use attributes and reflection

Entry Profile
The students who want to take this course should have:
types of hardware.
B had performance drawbacks, so in 1972 he rewrote B
and called it C. Therefore, C is categorized as both a
Chapter 1 Second and a Third Generation language. Thompson and
Ritchie rewrote the Unix operating system in C. In the
Introduction to C# years that followed, C was widely accepted and used
over different hardware platforms. This led to many
A computer needs a set of instructions called a program variations of C. In 1989, the American National
to perform any operation. A program needs to be written Standards Institute (ANSI), along with the International
in a specific language called programming language, so Standards Organization (ISO), approved a machine-
that the computer can understand the instructions. C# is independent and standard version of C.
one such programming language. In the early 1980s, Bjarne Stroustrup of Bell Labs
This chapter introduces you to C#. It explains how to developed the C++ language. In his own words, "C++
define classes and declare variables in C#. In addition, it was designed primarily so that my friends and I would
discusses how to create the object of a class. Further, it not have to program in assembly, C, or various modern
discusses how to write and execute C# programs. high-level languages. Its main purpose was to make
writing good programs easier and more pleasant for the
Objectives individual programmer.”
In this chapter, you will learn to: C++ was originally known as ‘C with classes’ because
 Identify C# basics two languages contributed to its design: C, which
 Declare variables provided low-level features, and Simula67, which
 Write and execute C# programs provided the class concept. C++ is an object-oriented
language. Other object-oriented languages are Java,
Smalltalk, and C# (pronounced as C sharp).
Introducing C# C# is a programming language introduced by Microsoft.
C# is intended to be a simple, modern, general-purpose,
Computer languages have come a long way since the object-oriented programming language. The name C# is
1940s. During that period, scientists punched inspired by the musical scale. On a musical scale, sharp
instructions into large, room-sized computer systems. (#) written against a note means that the note should be
These instructions were given in machine language, made half step higher in pitch. This is similar to the
which consisted of a long series of zeroes and ones. name C++, where ++ appended to C indicates an
These machine language instructions were executed enhanced version of the C language.
directly by the CPU. The machine language is called the
First Generation of computer languages.
The 1950s saw the emergence of the Second Generation Introducing Compilers
of computer languages, the assembly language.
Assembly language is easier to write than machine All languages have a vocabulary, which is a list of words
language but still extremely complicated for a common that have a specific meaning in that language. Languages
man. However, the computer could still understand only also have their own grammar rules, which state the rules
machine language. Therefore, the Assembler software for combining words to form sentences. This ensures
was developed to translate the code written in assembly that whatever is spoken in a particular language is
language into machine language. understood in the same way by all people who know the
In 1967, Martin Richard developed a language called language. Similarly, programming languages also have a
BPCL for writing operating systems. An operating vocabulary, which is referred to as the set of keywords of
system is a set of programs that manages the resources that language, and a grammar, which is referred to as the
of a computer and its interactions with users. The era of syntax.
the Third Generation of computer languages had arrived. Consider a scenario, where one person speaks in English
In 1970, Ken Thompson modified BPCL to create a new with the other person. However, the person who is
language called B. While working for Bell Laboratories, listening understands Chinese and not English.
Thompson teamed up with Dennis Ritchie and wrote an Therefore, he calls a translator who can translate the
initial version of the Unix operating system for a DEC words of English to Chinese. Similarly, computers
PDP-7 computer. cannot directly understand the instructions written in a
Dennis Ritchie was working on a project to further programming language. Therefore, you need a translator
develop the Unix operating system. He wanted a low to convert the instructions written in a programming
level language, like the assembly language, that could language to machine language.
control hardware efficiently. At the same time, he wanted A compiler is a special program that processes the
the language to provide the features of a high-level statements written in a particular programming language
language, that is, it should be able to run on different and converts them into machine language. Like
everything else in the computer, the compiler also
follows the Input-Process-Output (I-P-O) cycle. It takes
the programming language instructions as input. It
processes these instructions to convert them to machine
language. These instructions can then be executed by the
computer. This process of conversion is called
compilation.
The following figure shows the working of a compiler.

Working of a Compiler
For each programming language, there is a different Classes in C#
compiler available. For example, to compile a program
written in the C language, you require a C compiler. For C# classes are the primary building blocks of the
a Java program, you require a Java compiler. For C# language. C# also provides certain predefined set of
programs, you will use the csc compiler. classes and methods. These classes and methods provide
various basic functionalities that you may want to
implement in your application.
For example, if you want to perform some input/output
operations in your application, you can use predefined
classes available in the System.IO namespace.

A namespace is a collection of classes. C# provides


some predefined namespaces that contain classes, which
provide commonly used functionality. To use the classes
defined in these namespaces, you need to include the
relevant namespace in your program.

You can also create your own namespaces that contain


classes that you need to use across several programs.
In addition to using the predefined classes, you can also
define your own classes. Consider the following code,
which defines a class named Hello:
public class Hello
Using C# for Writing Programs {
public static void Main(string[]
Similar to the various programming languages, C# also args)
has some predefined keywords that can be used for {
writing programs. For example, class is a keyword in System.Console.WriteLine("Hello,
C# that is used to define classes. Keywords are reserved World! \n");
words that have a special meaning. Further, the syntax }
for C# defines rules for grammatical arrangement of }
these keywords. The preceding class declaration includes the method,
For example, the syntax of declaring a class in C# is: Main() that will display the message, “Hello,
class <class name> World!” on your screen. The preceding code includes
{ the following components:
...  The class keyword
}  The class name
In the preceding syntax, the braces, known as delimiters,  The Main() method
are used to indicate the start and end of a class body.  The System.Console.WriteLine()
method
 Escape sequences Method
Let us discuss these components in detail. Console is a class that belongs to the System
The class Keyword namespace. The Console class includes a predefined
The class keyword is used to declare a class. In the WriteLine() method. This method displays the
preceding code, the class keyword declares the class, enclosed text on the user’s screen. The Console class
Hello. has various other methods that are used for various
The Class Name input/output operations.
The class keyword is followed by the name of the The dot character (.) is used to access the WriteLine
class. In the preceding code, Hello is the name of the () method, which is present in the Console class of
class defined by using the class keyword. the System namespace.
Class Naming Conventions in C#
Class names should follow certain naming conventions Referencing a method in this form is also known as
or guidelines. A class name: referencing a method by using a fully qualified name.
 Should be meaningful (strongly recommended). The System.Console.WriteLine() statement
 Should ideally be a noun. can also be written as Console.WriteLine() if the
 Can use either the Pascal case or Camel case. In statement, using System is included as the first line
Pascal case, the first letter is capitalized and the of the code.
rest of the letters are in lower case, such as The following code snippet is an example of the
Myclass. In Camel case, the first letter is in Console.WriteLine() method:
lower case and the first letter of each Console.WriteLine("Hello, World!
subsequent word is capitalized, such as \n");
myClass or intEmployeeDetails. The preceding code snippet will display the following
Rules for Naming Classes in C# message on the screen:
In addition to the conventions, there are certain rules that Hello, World!
must be followed while naming classes in C#. The name
of classes:
 Must begin with a letter. This letter may be The WriteLine() method is used to write on the
followed by a sequence of letters, digits (0-9), screen. To read the input provided by the users, you can use
the ReadLine() method. The method will be discussed
or ‘_’. The first character in a class name cannot
later during the course.
be a digit.
 Must not contain an embedded space or a Escape Sequences
symbol like ? - + ! @ # % ^ & * ( ) [ ] { } . , ; : " To display special characters, such as the new line
' / and \. However, an underscore (‘_’) can be character or the backspace character, you need to include
used wherever a space is required. appropriate escape sequences in your code. An escape
 Must not use a keyword for a class name. For sequence is a combination of characters consisting of a
example, you cannot declare a class called backslash ( \ ) followed by a letter or a combination of
public. digits.
The Main() Method The following table lists some of the escape sequences
 The first line of code that a C# compiler looks provided in C#.
for in the source file is the Main() method.
This method is the entry point for an Escape Sequence Sequence Description
application. This means that the execution of \’ Single quotation mark
code starts from the Main() method. \ “ Double quotation mark
 The Main() method is ideally used to create \\ Backslash
objects and invoke the methods of various \0 NULL
classes that constitute the program. \a Alert
\b Backspace
string[] args in the preceding code is an \n New line
optional argument passed to the Main() method. \r Carriage return
Arguments that are passed to methods will be explained \t Horizontal tab
later in the course. \v Vertical tab

You must include a Main() method in a class to The Common Escape Sequences in C#
make your program executable. The following code snippet depicts the usage of the new
line escape sequence:
The System.Console.WriteLine()
Console.WriteLine("Hello \n World"); Miami, FL, \v 122001");
The preceding code snippet will display the following d. Console.WriteLine("Michelle
message on the screen: Gracias \n Email:
Hello michelle2012@abc.net \t 126,
World Parkway Street Boulevard, \t
Miami, FL, \t 122001");

Activity: Creating Classes


Problem Statement
Write a program to display the following details on the
screen:
Event: Tennis Match
Venue: Star Sports Complex
Time: 4:00 p.m. to 6:00 p.m
Solution
The following code will create the Event class with the
desired functionality:
public class Event
{
public static void Main(string[]
args)
{
Let’s Practice System.Console.WriteLine("Event:
Michelle wrote the following code snippet to print the \tTennis Match\n");
personal details for a resume: System.Console.WriteLine("Venue:
using System; \tStar Sports
public class Hello Complex\n");
{ System.Console.WriteLine("Time:
public static void Main(string[] \t4:00 p.m. to 6:00 p.m. \n");
args) }
{ }
//Insert code here
}
} Using Variables
She wants to print the following output: Consider a situation where you have to create a program
Michelle Gracias Email: michelle2012@abc.net that accepts two numbers from a user and displays the
126, Parkway Street Boulevard, sum of the numbers on the screen. Now, while reading
Miami, FL, the numbers provided by the user, you need to store
122001 these numbers somewhere in the memory so that you can
Help Michelle to select the correct code snippet that perform the add operation on the numbers. You can store
needs to be inserted in the Main() function to get the the numbers in the memory by using variables.
preceding output? The following figure shows the process of storing user
a. Console.WriteLine("Michelle input in the memory by using variables.
Gracias \t Email:
michelle2012@abc.net \n126,
Parkway Street Boulevard,
\nMiami, FL, \n122001");
b. Console.WriteLine("Michelle
Gracias \v Email:
michelle2012@abc.net \r 126,
Parkway Street Boulevard, \n
Miami, FL, \n 122001");
c. Console.WriteLine("Michelle
Gracias \t Email:
michelle2012@abc.net \v 126,
Using Variables to Store User Input
Parkway Street Boulevard, \v
In the preceding figure, a user provides 5 and 3 as input.
The digit 5 is stored in a variable, Num1 and digit 3 is
stored in a variable, Num2. A variable is a location in the
memory that has a name and contains the value. The
value could be an integer, such as 27, a decimal, such as
9.85, or a character, such as 'L'. A variable is associated
with a data type that defines the type of data that can be
stored in the variable.
For example, a variable called TennisPlayerName
will ideally store characters, whereas a variable called
High_Score will store numbers. A program refers to a
variable by its name.

Naming Variables in C#
In C#, the following rules are used for naming variables:
 A variable name must begin with a letter or an
underscore (‘_’), which may be followed by a
sequence of letters, digits (0-9), or underscores. Declaring and Initializing Variables
The first character in a variable name cannot be
a digit. You can declare and initialize variables by using the
 A variable name should not contain any following syntax:
embedded spaces or symbols, such as ? ! @ <data_type> <variable_name>=<value>;
# + - % ^ & * ( ) [ ] In the preceding syntax, the <data_type> represents
{ } . , ; : " ' / and \. However, an the kind of data type that will be stored in a variable and
underscore can be used wherever a space is <value> specifies the value that needs to be stored in
required, like High_Score. the variable.
 A variable name must be unique. For example, Consider the following statement that declares a
to store four different numbers, four unique variable:
variable names need to be used. int age = 1;
 A variable name can have any number of The preceding statement declares a variable named age
characters. of the int data type. In addition, the statement
 Keywords cannot be used as variable names. initializes the variable with the value, 1. The int data
For example, you cannot declare a variable type is used to store numeric data (integers).
named class as it is a keyword in C#. Consider the following statement:
Some examples of valid variable names are: char choice=‘y’;
 Game_level The preceding statement declares the variable choice
 High_score123 of the char data type and initializes the variable with
 This_variable_name_is_very_long the value, y.
Some examples of invalid variable names are:
 #score
 2strank

C# is a case-sensitive language. This means that the


TennisPlayerName variable is not the same as the
tennisplayername variable. In other words,
Uppercase letters are considered distinct from lowercase
letters.

Data Types in C#
C# provides various built-in data types. Built-in data
types are predefined data types that can be directly used
in a program to declare variables.
The following table lists some of the built-in data types
in C#.

Built-in Data #Bytes Values


Type
Char 2 0 to 65535
Int 4 -2,147,483,648 to
2,147,483,647 Memory Allocation in Value Type
Float 4 -3.402823E+38 to  Reference types: The reference type variables,
-1.401298E-45 instead of containing data, contain a reference
(for negative (address) to the data stored in the memory.
values) More than one reference type variable can be
1.401298E-45 to created to refer to the same memory location.
3.402823E+38 This means that if the value in the referenced
(for positive memory location is modified, all the referring
values) variables automatically reflect the changed
value. The example of a reference type is the
Double 8 -1.797693134862
string data type. The following figure shows
32E308 to
the memory allocation of a string value HELLO
-4.940656458412
47E-324 (for in a variable named Str.
negative values)
and
4.9406564584124
7E-324 to
1.7976931348623
2E308 (for
positive values)
Bool 1 True or False
String Memory Allocation in Reference Type
Variable length 0-2 billion
Unicode In the preceding figure, the Str variable stores
characters the address of the memory location where the
value, HELLO is stored in the memory.
The Commonly Used Built-in Data Types in C# The Dynamic Data Type
The #Bytes column in the preceding table specifies the In addition to the data types discussed earlier, C# also
bytes that are required to store the variable in the supports another data type called the dynamic data type.
memory. The Values column specifies the range of A variable declared with the dynamic data type can be
values that can be stored in the variable. used to store a value of any type. A variable of this data
type is declared by using the dynamic keyword.
Consider the following statement:
C# also provides user-defined data types. You will
dynamic id;
learn about user-defined data types in subsequent chapters.
In the preceding statement, the variable id is declared as
Types of Data Types a dynamic variable. This means that it can be used to
C# supports the following data types: store any type of value, as shown in the following
 Value types: The value types directly contain statements:
data. Some examples of value types are char,  id = 1; //id is considered
int, and float, which can be used for storing as int
alphabets, integers, and floating point values,  id = “A001”; //id is
respectively. When you declare an int considered as string
variable, the system allocates memory to store In the preceding statements, the variable, id inherits the
the value. The following figure shows the data type of the assigned value. In the first assignment
memory allocation of an int variable. statement, id is assigned an int value. Therefore, it is
treated as an integer. In the second assignment statement,
it is assigned a string value. Therefore, it is considered a
string.
Dynamic variables can use the methods associated with accepts the data in the string format. If you want to store
the data type they are resolved to. For example, a the data in any other format, you need to convert the data
dynamic variable containing a string value can access all type of the data provided by the user. For this purpose,
the string related attributes and methods, as shown in the you can use the Convert() method. This method
following code snippet: informs the compiler to convert one data type to the
dynamic d = “Sample”; other. This is known as explicit conversion.
int len = d.Length; For example, consider the following code snippet:
int Number;
Number = Convert.ToInt32
The Length attribute of a string stores the length of
a string.
(Console.ReadLine());
Here, the Convert.ToInt32() method converts the
For dynamic variables, type checking is done at run time
data provided by the user to the int data type.
and not at compile time. This is known as duck typing.
For example, consider the following code snippet: In addition to explicit conversion, there are instances
dynamic var = 1; when the compiler performs implicit conversions, which
int len = var.Length; are done automatically (without any explicit coding). For
In the preceding code snippet, no error will be thrown at example, implicit conversion converts the int data type
compile time because dynamic variables are allowed to to float or float data type to int, automatically.
access members associated with any type. However, at
run time the code will generate an error, as var is
resolved as an int type and length property is not
associated with int data type.

Let’s Practice
Adrian created the following Book class, where the
InputDetails() method takes the input details of
the book:
Accepting and Storing Values in using System;
Variables class Book
{
At times programs need to accept a value from a user private String BookName;
and store the value in a variable to perform some private int cost;
processing. To understand how to accept a value from a public void InputDetails()
user and store it in a variable, consider the following {
code snippet: Console.WriteLine("Enter the book
String name; name");
name = Console.ReadLine(); BookName = Console.ReadLine();
In the preceding code snippet, the Console.WriteLine("Enter the cost of
Console.ReadLine() method is used to accept data the book");
from the user and store it in a variable named name. The //Insert code here
Console.ReadLine() method is a method of the }
Console class, which is a part of the System }
namespace. Help Adrian to select the correct code snippet that needs
The Console.ReadLine() method, by default, to be inserted in the InputDetails() method so that
he can enter the cost of the book.
a. cost= Console.ReadLine();
b. cost= Convert.ToInt32
(Console.ReadLine());
c. cost= Convert.ToInt
(Console.ReadLine());
d. cost=Convert.ToInt64
(Console.Read());

Writing and Executing a C# Program


A C# program can be written by using the Windows
Notepad application. After creating a C # program in the Output of the Program
Notepad application, you need to compile and execute Typical building blocks of a C# program are:
the program to get the desired output. The compiler  The using keyword
converts the program’s source code to machine code,  The class keyword
such that the computer can understand the instructions in  The comment entry
the program.  The member variables
 The member functions
Besides Notepad, you can also use any other text  The instantiating class
editor to write a C# program. In addition, you can use The using Keyword
other tools as well. You will learn more about one of these The using keyword is used to include namespaces in
tools in the subsequent chapters. the program. Keywords are reserved words that have a
special meaning. The statement, using System,
declares that you can refer to the classes defined in the
Creating a Sample C# Program System namespace without using the fully qualified
Consider the following code, which declares the Car name. You can write multiple using statements in your
class and creates a MyCar object of the class: program to include more than one namespace in the
program.
The class Keyword
The class keyword is used to declare a class. In the
preceding code, the class keyword defines the class,
Car. The braces, known as delimiters, are used to
indicate the start and end of a class body.
The Comment Entry
Comments are used to explain the code in a program.
Compilers ignore the comment entries included in a
program. The symbol ‘//’ treats the rest of code within
the same line as a comment. If a comment entry spans
more than one line, it has to be enclosed within ‘/*’ and
‘*/’.
The following examples show the usage of comment
entries in C#:
 // Single Line Comment
When you compile and execute the preceding code, the  /* Multiple
console window is opened. When you provide an input Line
to the program, an output, similar to that shown in the Comment */
following figure is generated. The Member Variables
Data members of a class are called member variables. In
the given code, the Car class has two member variables,
Engine and NoOfWheels. These variables are used to
store the data provided by the user. The variables are
declared as private. This means that the variables are
accessible only inside the class in which they are
declared. Any code outside the class cannot access the
private variables declared in the class.
The Member Functions
Member methods are also known as member functions.
The code for the Car class contains two member
functions, InputDetails() and
DisplayDetails(). Both the methods are declared
as public methods. This means that the methods are
accessible from any other class outside the Car class.
The InputDetails() and DisplayDetails()
methods are declared with the return type, void. This
means that the methods do not return any value. The
GetEngine() method is declared with the return type,
string. This means that the method returns a string
value.
The InputDetails() method prompts the user to
enter the engine model and number of wheels in the
vehicle. It then stores these details in the respective
variables. The DisplayDetails() method displays
the values stored in the member variables. Compiling and Executing a C#
Program
You will learn more about methods in the subsequent You need to perform the following steps to compile and
chapters. execute a C# program:
The Instantiating Class 1. Save the code written in Notepad with a .cs
The MainClass class contains the Main() method. extension.
This class is used to instantiate the Car class. The first 2. Open the Visual Studio Command Prompt
line of code that a C# compiler looks for is the Main() window to compile this program.
method. 3. In the Visual Studio Command Prompt window,
To implement the functionality of a class, you need to change the current directory to the directory
create an object of the class. where the program file is saved.
Consider a class named Car. To create an object named
MyCar of the Car class, the following statement can be You can use the cd <directory
used in the Main() method: name> command to change the directory. You can
Car MyCar = new Car(); use the command, cd.. to move to the parent
The new keyword is used to allocate memory to an directory. Similarly, you can use the command, cd
object at run time. The member functions of the class are \ to move to the root directory.
accessed through an object of the class by using the “.” 4. Compile the program file by using the
operator, as shown in the following code snippet: following command at the command prompt:
MyCar.InputDetails(); csc MainClass.cs
MyCar.DisplayDetails(); 5. To execute the code, type the following
In the preceding example, the object name and the “.” command:
operator are used to access the member functions of the MainClass.exe
Car class. or
MainClass
{
string TennisPlayerName;
int Rank;
public void PrintPlayerDetails
()
{
Console.WriteLine("The details
of the Tennis Players are:
");
Console.WriteLine("Name: ");
Console.WriteLine
(TennisPlayerName);
Console.WriteLine("Rank: ");
Console.WriteLine(Rank);
}
public void GetPlayerDetails ()
{
Console.WriteLine("Enter the
Let’s Practice details of the Tennis
Players ");
Console.WriteLine("\n Enter
TennisPlayer Name: ");
TennisPlayerName=Console.ReadL
ine();
Console.WriteLine("Rank: ");
Rank=Convert.ToInt32
(Console.ReadLine());
}
}
class Tennis
{
public static void Main(string
[] args)
{
TennisPlayer P1=new
TennisPlayer();
P1.GetPlayerDetails();
P1.PrintPlayerDetails();
Activity: Writing and Executing a C# }
Program }
3. Select File→Save to save the program. The
Problem Statement Save As dialog box appears.
David is the member of a team that is developing the 4. Enter Tennis.cs in the File name combo box.
Automatic Ranking software for a tennis tournament. He The file name is saved with a .cs extension,
has been assigned the task of creating a program that signifying that it is a C# program.
should accept the following details of a tennis player and
display the same on the screen: You can save the file in any folder of your
 Name choice.
 Rank 5. Close the Tennis.cs – Notepad window.
You need to help David to create the program. 6. Open the Visual Studio Command Prompt
Solution window to compile this program.
To create the required program, David needs to perform 7. In the Visual Studio Command Prompt window,
the following steps: change the current directory to the directory
1. Open Notepad. where the program is saved.
2. Write the following code in Notepad: 8. Type the following command at the command
using System; prompt to compile the Tennis.cs program:
class TennisPlayer csc Tennis.cs
9. Type the following command at the command and color. Once the input is provided, the application
prompt to execute the compiled program: should draw the shape with the same area and color as
Tennis.exe entered by the user.
The following figure displays the output of the You, as part of the development team, have to define the
executed program. Geometrical_Shapes class that should have
methods to accept the input from the users, display the
input as entered by the user, and display the shapes with
the same color and area. You have written the following
code:
class Geometrical_Shapes
{
Double Area;
string shape;
string Color;
public:
void GetInput()
Output of the Program {
//Code to accept the user inputs and
store the values in
Summary //the corresponding variables
}
In this chapter, you learned that: void Display()
 The compiler software translates a program {
written in a language, such as C#, into the //Code to display the details of the
machine language. shape such as
 In C#, a class is created by using the class //no_of_coordinates, area, and color
keyword. It is identified by a name called the }
class name. }
 The Main() method is the first method, which
You thought of showing this class to your supervisor
is executed in a C# program. before adding the method to draw the shapes. However,
 The Console.WriteLine() method is your supervisor told you that the class definition
used to display text on the screen. contains errors. In addition, he asked you to complete the
 Escape characters are used to display special methods.
characters such as the newline character. Now, you need to fix the errors and complete the
 A variable is a named location in the memory GetInput() and Display() methods. You also
that contains a specific value.
need to write the Main() method so that the code can
 A data type defines the type of data that can be
be compiled and executed.
stored in a variable.
 The two types of data types are value type and
reference type.
 The ReadLine() method is used to accept
input from the user. Exercise 2
 The using keyword is used to include
Jim is developing software for automating the slot
namespaces in a program. booking process for a video game parlor. Customers fill
 A namespace contains a set of related classes. the Booking Request form with the details of the game,
 Member variables are declared inside the class such as the name, number of players, and complexity
body. level. They hand over the form to the booking officer at
 Comment entries are notes written by a the parlor. Depending on the availability, the booking
programmer in code so that others reading that officer reserves the time slots and the play station for
code can understand it better. customers.
Identify the involved classes and objects, and their
attributes. Write methods in the class to accept the game
Exercises details and display them.
Exercise 1
Diaz Entertainment, Inc. has to develop a software
application for young children that would enable them to
identify and distinguish shapes and colors. The
application should ask the name of the shape, its area,
Exercise 3
Predict the output of the following code snippet:
using System;
class Myclass
{
static void Main() Exercise 5
{ TechnoSoft, a leading software company, has developed
string Answer="Y"; an application for maintaining the scores of games in a
string Response_code="66"; video game parlor. If the new score is greater than the
int Counter=60; stored top score, the following program should
Console.WriteLine(Answer); interchange the values of the variables Top_score and
Console.WriteLine(Response_code); New_score. However, the program does not generate
Console.WriteLine(Counter); the desired output. Identify the error in the following
Console.ReadLine(); program and write the correct code:
} using System;
} class Interchange
{
int Top_score;
int New_score;
int Temp;
Exercise 4 void Swap()
An automobile company has developed an application {
for maintaining the number of wheels in a vehicle. Top_score=5;
Predict the output of the following code of the New_score=10;
application: Temp=top_score;
using System; New_score=Top_score;
class Vehicle Top_score=New_score;
{ }
public int Number_of_tyres; void Display()
} {
class MyVehicle Console.WriteLine("The new value of
{ top score is:");
static void Main(string[] args) Console.WriteLine(Top_score);
{ Console.WriteLine("The old value of
Vehicle Motorcycle= new Vehicle(); top score was:");
Vehicle Car = new Vehicle(); Console.WriteLine(New_score);
Console.WriteLine("Enter the number }
of wheels in a car:"); static void Main()
Car.Number_of_tyres=Convert.ToInt32 {
(Console.ReadLine()); Interchange I1;
Console.WriteLine("Enter the number I1.Swap();
of wheels in a I1.Display();
Motorcycle:"); Console.ReadLine();
Motorcycle.Number_of_tyres=Convert.T }
oInt32 }
(Console.ReadLine());
Console.WriteLine("\n");
Console.Write(Car.Number_of_tyres);
Console.WriteLine(" :is the number
of wheels in a Car Exercise 6
\n"); As a part of the team that is developing software for a
Console.Write library, you have been assigned the task of writing a
(Motorcycle.Number_of_tyres); program. The program should accept the following book
Console.WriteLine(" :is the number details:
of wheels in a  Book Number as int
Motorcycle \n");  Book Category (Fiction or Nonfiction) as
Console.ReadLine(); string
}  Author Name as string
}  Number of copies available as int
Write a C# program to accept and display the preceding
book details.

Exercise 7
Write a C# program that accepts distance in kilometers,
converts it into meters, and then displays the result.

Exercise 8
Write a program that displays “Congratulations! You
have cleared this Level. Entering Level 2...” in red color.
The output of this program is shown in the following
figure.

The Output of the Program

Reference Reading
Introducing C#

Reference Reading: Books Reference Reading: URLs


Simon Robinson, msdn.microsoft.com/en-us/
Professional C# vcsharp/aa336809.aspx

Using Variables

Reference Reading: Books Reference Reading: URLs


Simon Robinson, http://www.csharp-
Professional C# station.com/Tutorials/
Lesson01.aspx

Writing and Executing a C# Program

Reference Reading: Books Reference Reading: URLs


Herbert Schildt, C# 3.0: http://www.csharp-
The Complete Reference station.com/Tutorials/
Lesson01.aspx
Chapter 2
Operators and Programming
Constructs
When writing a program, you sometimes need to
compare data values and compute results. For this
purpose, operators are used. Also, programs often
involve decision-making and iterative tasks. You can use
conditional constructs for decision making and looping
constructs for iterative tasks in your programs.
This chapter discusses the various types of operators
used in the C# language. In addition, the chapter
discusses the various conditional and looping constructs
supported by C#.

Objectives
In this chapter, you will learn to:
 Use various operators
 Use conditional constructs
 Use looping constructs

Using Various Operators


Consider an example, where you need to develop a
program for displaying the result and rank of the
students in a class. To compute result and ranks, the Operator and Operands
application needs to perform some calculations and You can use the following types of operators in your C#
comparisons. You can use various operators in your C# programs:
program and use them to compute the results and ranks  Arithmetic operators
of the students.  Arithmetic assignment operators
Operators like + (addition) and ? (subtraction) are used  Unary operators
to process variables and return a value. An operator is a  Comparison operators
set of one or more characters that is used for  Logical operators
computations or comparisons. Operators can change one
or more data values, called operands, into a new data
value. Arithmetic Operators
Consider the following expression: Arithmetic operators are used to perform arithmetic
X+Y operations on variables. The following table describes
The preceding expression uses two operands, X and Y, the commonly used arithmetic operators.
and an operator, +, to add the values of both the
variables. The following figure shows the operator and Operator Description Example
operands used in the preceding expression.
+ Used to add two X=Y+Z;
numbers If Y is equal to 20
and Z is equal to
2, X will have the
value 22.
- Used to subtract X=Y-Z;
two numbers If Y is equal to 20
and Z is equal to
2, X will have the
value 18.
* Used to multiply X=Y*Z;
two numbers If Y is equal to 20 Some Common Arithmetic Assignment Operators
and Z is equal to
2, X will have the
value 40.
/ Used to divide X=Y/Z;
one number by If Y is equal to 21
another and Z is equal to
2, X will have the
value 10.
% Used to divide X=Y%Z;
two numbers and If Y is equal to 21
return the and Z is equal to
remainder. The 2, X will contain
operator is called the value 1.
as modulus
operator

The Commonly Used Arithmetic Operators

Unary Operators
Arithmetic Assignment Operators Unary operators are used to increment or decrement the
value of an operand by 1. The following table explains
Arithmetic assignment operators are used to perform the usage of the increment and decrement operators.
arithmetic operations on two given operands and to
assign the resultant value to any one of them.
The following table lists the usage and describes the
commonly used arithmetic assignment operators.

Operator Usage Description


+= X+=Y; Same as:
X = X + Y;
-= X-=Y; Same as:
X = X - Y;
*= X*=Y; Same as:
X = X * Y;
/= X/=Y; Same as:
X = X / Y;
%= X%=Y; Same as:
X = X % Y;
Comparison Operators
Comparison operators are used to compare two values
and perform an action on the basis of the result of that
comparison. Whenever you use a comparison operator,
the expression results in a boolean value, true or
false. The following table explains the usage of some
commonly used comparison operators.

Some Common Unary Operators

Some Common Comparison Operators


Logical Operators Let’s Practice
Logical operators are used to evaluate expressions and Match the relations in column A with the arithmetic
return a boolean value. The following table explains the operators in column B.
usage of logical operators.

Using Conditional Constructs


The ability to take decisions is fundamental to human
beings. Decision-making can be incorporated into
programs as well. This helps in determining the
sequence in which a program will execute instructions.
You can control the flow of a program by using
conditional constructs. Conditional constructs allow you
to execute selective statements based on the result of the
expression being evaluated. The various conditional
constructs that can be included in a C# program are:
 The if...else construct
 The switch...case construct

The if...else Construct


Some Common Logical Operators The if statement in the if...else conditional
construct is followed by a logical expression where data
is compared and a decision is made on the basis of the
result of the comparison. The following statements
Namespaces help you to create logical groups of
depict the syntax for the if...else construct:
related classes and interfaces, which can be used by any
if (expression) language targeting the .NET Framework. Namespaces
{ allow you to organize your classes so that they can be
statements; easily accessed in other applications.
}
else Namespaces can be used to avoid any naming conflicts
{ between classes, which have the same names. For example,
statements; you can use two classes with the same name in an
} application provided they belong to different namespaces.
Consider an example where you have to decide if you You can access the classes belonging to a namespace by
want to have dinner or you want to go to sleep. The simply importing the namespace into the application.
condition on which you will make a decision will be
your hunger. If you are hungry, you will have dinner; The .NET Framework uses a dot (.) as a delimiter between
else you will go to sleep. classes and namespaces. For example, System.Console
The following code snippet shows the decision making represents the Console class of the System namespace.
of the preceding example by using the if...else Namespaces are also stored in assemblies.
construct: The preceding code checks whether the age of the player
if (hungry==true) is less than 12. The condition in the if statement checks
{ the age of the player, and if the condition is true, the
Console.WritLine(“Go and have statements in the if block are executed. If the condition
Dinner!”); in the if statement is false, the statements in the else
} block are executed.
else The output of the preceding code will be:
{ Enter Your Age:
Console.WriteLine(“Go to Sleep”); 14
} Play the Game
The following code shows the use of the if...else The else block in the if...else construct is
construct: optional and can be omitted. The following code snippet
using System; shows an example of an if...else construct without
the else block:
namespace video int var = 5;
{ if (var > 0)
class Game Console.WriteLine(“var is a positive
{ number.”);
static void Main(string[] args) The if...else constructs can also be nested inside
{ each other.
int Age; Consider an example where you want to buy a specific
Console.WriteLine("Enter Your model of Nike shoes. You go to a shoe shop and ask the
Age: "); shopkeeper if shoes of Nike brand are available. If they
Age = Convert.ToInt32 have the shoes, you will ask for the model number that
(Console.ReadLine()); you are looking for. If the requested shoe model is
if (Age<12) available with them, then you will buy the shoes; else,
{ you will leave the shop. Therefore, in this situation you
Console.WriteLine("Sorry!
have to make two decisions one after the other. You can
This game is for children above 11
take successive decisions in your program by using the
years.");
nested if...else construct.
}
else The following code snippet shows the implementation of
{ the preceding example by using the nested if...else
Console.WriteLine("Play the construct:
Game."); if (Nike==available)
} if (Model==M007)
} Console.WriteLine(“Buy Shoe!”);
} else
} Console.WriteLine(“Leave the shop!”);

If the if and else part of the if...else construct


contains single statements, then there is no need to enclose condition evaluates to true, the second condition is not
the statements within curly braces. However, if there are evaluated.
multiple statements in the if and else part, then these
statements should be enclosed within curly braces.
The following code snippet shows the use of a nested
if...else construct:
int Number1, Number2, Number3;
Number1 = 10;
Number2 = 20;
Number3 = 30;
if (Number1 > Number2)
{
if (Number1 > Number3)
Console.WriteLine(“Number1 is the
greatest.”);
else
Console.WriteLine(“Number3 is
the greatest.”);
}
else
{
if (Number2 > Number3) The switch...case Construct
Console.WriteLine(“Number2 is Another conditional construct available in C# is the
the greatest.”); switch...case construct. It is used when you have
else
to evaluate a variable for multiple values.
Console.WriteLine(“Number3 is
The following code snippet depicts the syntax for the
the greatest.”);
switch...case construct:
}
switch(VariableName)
The preceding code snippet displays the greatest of the
{
three numbers, Number1, Number2, and Number3.
case ConstantExpression_1:
The nested if...else construct can also be statements;
represented by using logical operators. The preceding break;
example of the Nike shoe can be changed to an case ConstantExpression_2:
if...else construct by using logical operators. The statements;
following code snippet shows the converting of the break;
nested if...else construct to an if...else ...
construct by using logical operators: case ConstantExpression_n:
if ((Nike==available) && statements;
(Model==M007)) break;
Console.WriteLine(“Buy Shoe!”); default:
else statements;
Console.WriteLine(“Leave the shop!”); break;
The following code snippet shows the use of an }
if...else construct by using logical operators: When the switch statement is executed, the variable
int Number1, Number2, Number3; given in the switch statement is evaluated and
Number1 = 10; compared with each case constant. If one of the case
Number2 = 20; constants is equal to the value of the variable given in
Number3 = 30; the switch statement, control is passed to the statement
if ((Number1 > Number2) && (Number2 > following the matched case statement. The break
Number3)) statement is used to exit the switch statement. This
Console.WriteLine(“Number1 is the
prevents the execution of the remaining case structures
greatest”);
by ending the execution of the switch...case
In the preceding code snippet, the
construct. If none of the cases match, the statements
Console.WriteLine(“Number1 is the
under the default statement are executed.
greatest”); statement is executed only if both the
The keyword switch is followed by the variable in
conditions around the && operators evaluate to true.
parentheses, as shown in the following code snippet:
switch(var)
In case of a logical OR operator (||), if the first Each case keyword is followed by a possible value for
the variable, as shown in the following statement:
case constantValue:
The data type of the constant should match the data type
of the variable being evaluated by the switch
construct. Before entering the switch construct, a
value should be assigned to the switch variable.
You can replace a complex if...else construct with
the switch...case construct when you want to
check multiple values for a variable. The following code
snippet is an example of the nested if...else
construct:
int Grade;
Grade = 3;
if (Grade == 1)
Console.WriteLine("OK");
else if (Grade == 2)
Console.WriteLine("Good");
else if (Grade == 3)
Console.WriteLine("Excellent");
else
Console.WriteLine("Invalid value of
Grade");
The preceding code can be replaced by a simple
switch...case construct, as shown in the following
code snippet:
int Grade;
Grade = 500;
switch(Grade)
{
case 1:
Console.WriteLine("OK");
break;
case 2:
Console.WriteLine("Good");
break; Let’s Practice
case 3:
Console.WriteLine("Excellent");
break;
default:
Console.WriteLine("Invalid value
of Grade");
break;
}
The switch...case construct evaluates an
expression only once at the top of the structure, where as
the if...else construct evaluates the expression for
each if statement.

The if...else structure can be substituted with a


switch...case structure only if each else...if
statement in the if...else construct evaluates the same
expression.
Console.WriteLine
("Yellow");
}
else if ((c1 == "RED" && c2
== "BLUE") || (c1 == "BLUE" && c2 ==
"RED"))
{
Console.ForegroundColor =
ConsoleColor.Magenta;
Console.WriteLine
("Magenta");
}
else if ((c1 == "BLUE" && c2
== "GREEN") || ( c1 == "GREEN" && c2
== "BLUE"))
{
Console.ForegroundColor =
ConsoleColor.Cyan;
Activity: Displaying Colored Output Console.WriteLine
("Cyan");
Problem Statement }
Write a program that accepts two primary colors from else
the user, adds them, and displays the output in the new {
color combination. If the user enters an incorrect color, Console.WriteLine("Colors
the program should display “Colors you entered are not you entered are not the correct RGB
the correct RGB color combination.”. color combination.");
}
Solution }
using System; public static void Main()
namespace addPrimaryColors {
{ colorChange cC = new
class colorChange colorChange();
{ cC.acceptDetails();
string c1, c2; cC.AddColors();
public void acceptDetails() }
{ }
Console.WriteLine }
("Instructions:");
The following figure depicts the output of the executed
Console.WriteLine("1. Please
program.
enter the two primary colors you want
to add." + "\n2. The list of primary
colors includes: \n RED \n GREEN \n
BLUE");
Console.WriteLine("3. Please
enter the color in uppercase only.");
Console.WriteLine("Please
enter the first color:");
c1 = Console.ReadLine();
Console.WriteLine("Please
The Output
enter the second color:");
c2 = Console.ReadLine();
}
public void AddColors() Using Loop Constructs
{ Loop constructs are used to execute one or more lines of
if ((c1 == "RED" && c2 == code again and again. In C#, the following loop
"GREEN") || (c1 == "GREEN" && c2 == constructs can be used:
"RED" ))  The while loop
{  The do...while loop
Console.ForegroundColor =  The for loop
ConsoleColor.Yellow;
4. var = 120 + 10 Value of
variable is:
The while Loop 130
The while loop construct executes a block of 5. var = 130 + 10 Value of
variable is:
statements till the condition given in the while loop
140
holds true. The while statement always checks the
6. var = 140 + 10 Value of
condition before executing the statements within the
variable is:
loop. When the execution reaches the last statement in
150
the while loop, the control is passed back to the
7. var = 150 + 10 Value of
beginning of the loop. If the condition still holds true,
variable is:
the statements within the loop are executed again. The
160
execution of the statements within the loop continues
until the condition evaluates to false. 8. var = 160 + 10 Value of
variable is:
The following statements depict the syntax for the
170
while loop construct:
while (expression) 9. var = 170 + 10 Value of
variable is:
{
180
statements;
} 10. var = 180 + 10 Value of
variable is:
The following code provides an example of the while
190
loop construct:
using System; 11. var = 190 + 10 -
class Variable
{ The Dry Run Table
static void Main(string[]args) The following figure shows the output of the preceding
{ code.
int var;
var = 100;
while (var < 200)
{
Console.WriteLine ("Value
of variable is: {0}", var);
var = var + 10;
}
}
}
The preceding code creates an integer variable named
var and assigns the value 100 to it. The while
statement checks whether the value of var is less than
200. If the condition evaluates to true, the statements
within the while loop are executed. This process
continues till the value of var is less than 200.
The following dry run table can be used to test the values
of the preceding code.

S. No Change in the Output


Value of the
Variable var Output of the Program
1. var = 100 Value of You can use the break statement to exit the while
variable is: loop structure. The following code snippet shows the
100 usage of the break statement:
2. var = 100 + 10 Value of int var;
variable is: var = 100;
110 while (true)
3. var = 110 + 10 Value of {
variable is: Console.WriteLine (“Value of var: {0}
120 ” + var);
var = var + 10; the loop */
if (var == 200) In the preceding example, the condition is checked after
break; the statements in the do...while loop structure is
} executed. Therefore, the statements within the
In the preceding code snippet, the while (true) do...while loop will print the value of var once.
statement will always evaluate to true and the while Since the condition in the while loop evaluates to false,
block will run an indefinite number of times. In such a the program will not execute the statements written in
case, the break statement is used to exit the while the do...while loop again.
loop block on the basis of the condition given within the This difference between the do...while and while
while block. In the preceding example, the control loop constructs is shown in the following figure.
moves out of the while loop when the value of var
becomes equal to 200.

Difference in Execution of the do...while and while loops

The do...while Loop


The do...while loop construct is similar to the
while loop construct. Both will continue looping until
the loop condition becomes false. However, the
statements within the do...while loop are executed
at least once, as the statements in the block are executed
before the condition is checked.
The following statements show the syntax for the
do...while loop construct:
do
{
statements;
}while(expression);
Consider the following example of the do...while
loop construct:
int var; The for Loop
var = 100;
do Usually, the for loop structure is used to execute a
{ block of statements for a specific number of times.
Console.WriteLine (“Value of var: ” + However, it can also be used to execute a block of
var); /* will print the statements indefinitely. The following statements show
value 100 */ the syntax of the for loop construct:
var = var + 10; // value of var The for loop structure is used to execute a block of
becomes 110 statements for a specific number of times. The following
} statements show the syntax of the for construct:
while (var < 100); /* 110 < 100 is for (initialization; termination;
not true. Hence, program comes outof
increment/decrement)
{
statements;
}
In the for loop, first of all the initialization expression
is executed. It is executed only once at the beginning of
the loop. Then the termination expression is evaluated
for each iteration to determine when to terminate the
loop. When the expression evaluates to false, the loop
terminates. Then, through the loop, the statements within
the body of the for loop are executed. Finally, the
increment or decrement expression gets invoked for each
iteration. All these components are optional.

Sequence of Execution of the for loop


The following code is an example of the for loop
structure that displays integers from 10 to 19:
using System;
class Variable
{
static void Main(string[] args)
{
You can create an infinite loop by keeping all the three int var;
expressions blank, as shown in the following code for (var=10; var <20; var++)
snippet: {
for ( ; ; ) Console.WriteLine ("Value of
{ variable is:{0} ", var);
statements }
} }
The sequence of execution of a for loop construct is }
shown in the following figure. The following dry run table can be used to test the values
of the preceding code.

S. No Change in the Output


Value of the
Variable var
1. var = 10 Value of
variable is:
10
2. var = 10 + 1 Value of
variable is:
11
3. var = 11 + 1 Value of
variable is:
12
4. var = 12 + 1 Value of
variable is:
13
5. var = 13 + 1 Value of
variable is:
14
6. var = 14 + 1 Value of
variable is:
15
7. var = 15 + 1 Value of
variable is:
16
8. var = 16 + 1 Value of
variable is:
17
9. var = 17 + 1 Value of
variable is:
18
10. var = 18 + 1 Value of
variable is:
19
11. var = 19 + 1 -
The break and continue Statements
The Dry Run Table
The following figure shows the output of the preceding There may be situations where there is a need to exit a
code. loop before the loop condition is checked after an
iteration. The break statement is used to exit from the
loop. It prevents the execution of the remaining loop.
The continue statement is used to skip all the
subsequent instructions and take the control back to the
loop.
The following code accepts five numbers and prints the
sum of all the positive numbers:
using System;
class BreakContinue
{
static void Main(string[] args)
{
int incr, SumNum, number;
for (SumNum = number = incr = 0;
incr < 5; incr += 1)
{
Console.WriteLine("Enter a
positive number");
number = Convert.ToInt32
(Console.ReadLine());
if (number <= 0) // Non-
positive numbers
Output of the Program continue; // Continue to
inctr+=1 in the forloop
SumNum = SumNum + number;
}
Console.WriteLine("The sum of
positive numbers entered is {0}",
SumNum);
}
}
The following figure displays the output of the preceding
code.
Predict the output of the following code:
using System;
namespace prime
{
class MyTest{
static void Main(){
for (int i = 2; i <= 5; i++){
if (i < 3){
continue;
}
Console.WriteLine(i);
}
Output of the Program
}
}
}

Activity: Fibonacci Series Using


Loop Constructs
Problem Statement
Write a program that generates the Fibonacci series up to
200.

In Fibonacci series, each new number in the series


is the sum of the two numbers before it. The Fibonacci
series in the range 1 to 200 will be:1, 1, 2, 3, 5, 8,..144.
Solution
using System;
class Fibonacci{
Let’s Practice static void Main(string[] args) {
int number1;
Question 1 int number2;
Consider the following code snippet: number1=number2=1;
static void Main(string[] args) Console.WriteLine("{0}",
{ number1);
int x=0; while (number2 < 200)
//Insert code here {
{ Console.WriteLine(number2);
Console.WriteLine("Value of x number2 += number1;
is:" +x); number1 = number2-number1;
x = x + 5; }
} }}
} The following figure depicts the output of the executed
The output desired from the preceding code snippet is: program.
Value of x is: 0
Value of x is: 5
Value of x is: 10
Value of x is: 15
Value of x is: 20
Select the correct options that can be inserted in the code
snippet so as to generate the preceding output.
a. while(x<=20)
b. while(x<=0)
c. while(x=0)
d. while(x<20)
Question 2
conditional constructs in C# are:
 if...else
 switch...case
 The if statement in the if...else conditional
construct is followed by a logical expression
where data is compared and a decision is made
on the basis of the result of the comparison.
 The switch...case construct is used when
you have to evaluate a variable for multiple
values.
 Looping constructs are used when you want a
section of a program to be repeated a certain
number of times. C# offers the following
looping constructs:
 while
The Output
 do...while
1. State whether the following statement is true or  for
false.  The break and continue statements are
The continue statement if used in the while
used to control the program flow within a loop.
and do...while loop causes the program
control to pass to the top of the loop avoiding
the other statements in the loop. Exercises
2. State whether the following statement is true or
false. Exercise 1
A termination expression is evaluated at each Write a program to identify whether a character entered
iteration of the for loop. by a user is a vowel or a consonant.
3. Write a program to:
a. Accept five numbers and display their
sum and average.
b. Accept three numbers and display the
largest. Exercise 2
c. Accept a number and check if it is Write a program to identify whether the number entered
divisible by five. by a user is even or odd.
d. Accept ten numbers and display the
largest.
e. Accept five numbers and check if they
are even or odd.
Exercise 3
Write a program to accept a number from the user and
Summary display all the prime numbers from one up to the number
entered by user.
In this chapter, you learned that:
 Operators are used to compute and compare
values and test multiple conditions.
 You use arithmetic operators to perform
arithmetic operations on variables like addition,
subtraction, multiplication, and division.
Exercise 4
Write a program to accept two numbers and check if the
 You can use arithmetic assignment operators to
first is divisible by the second. In addition, an error
perform arithmetic operations and assign the
message should be displayed if the second number is
result to a variable.
zero.
 The unary operators, such as the increment and
decrement operators, operate on one operand.
 Comparison operators are used to compare two
values and perform an action on the basis of the
result of the comparison.
 Logical operators are used to evaluate
Exercise 5
Write a program to accept two numbers and display the
expressions and return a bool value.
quotient as a result. In addition, an error message should
 Conditional constructs are used to allow the
be displayed if the second number is zero or greater than
selective execution of the statements. The
the first number.
display “This application will allow you to
create a meaningful word from jumbled
letters.”.
4. If the user enters option 4, the program should
Exercise 6 display “This application will allow you to
Write a program to enter a number from 1 to 7 and create multiple words from a single word. Each
display the corresponding day of the week. correct word will increase your score by 1.”.

Exercise 7
Write a program to display the highest of any 10
numbers entered. Reference Reading
Using Various Operators

Reference Reading: Books Reference Reading: URLs


Exercise 8 Herbert Schildt, C# 3.0: http://msdn.microsoft.com/
Write a program to print the product of the first 10 even The Complete Reference en-us/library/6a71f45d
numbers. (VS.80).aspx

Using Conditional Constructs

Reference Reading: Books Reference Reading: URLs


Exercise 9
Herbert Schildt, C# 3.0: http://www.astahost.com/
Enter a year and determine whether the year is a leap
The Complete Reference info.php/c-tutorial-
year or not. A leap year is a non century year that is
lesson-3-programming-
divisible by 4. A century year is a year divisible by 100,
constructs_t15392.html
such as 1900. A century year, which is divisible by 400,
such as 2000, is also a leap year.
Hint: If a year is divisible by 4 and is not divisible by Using Loop Constructs
100 or divisible by 400, it is a leap year.
Reference Reading: Books Reference Reading: URLs
Herbert Schildt, C# 3.0: http://www.aspfree.com/c/
The Complete Reference a/C-Sharp/C-Sharp-
Simplified-part-2-Methods-
Exercise 10 Programming-
Write a program that displays a menu as shown in the Constructs/4/
following figure.

The Menu
The program should implement the following features:
1. If the user enters the option 1, the program
should display “This application will allow you
to create a pattern in pyramid structure.”.
2. If the user enters option 2, then the program
should display “This application will allow you
to add two primary colors and displays the third
color.”.
3. If the user enters option 3, the program should
The following code shows the use of the public access
specifier:
using System;
Chapter 3 class Bike
{
Working with Class Members public string BikeColor; /*Since
the variable is public, it can be
You have already learned that classes contain attributes accessed outside the class
and methods. However, in addition to attributes and definition.*/
methods, classes contain other members, such as }
constructors, destructor, and properties. class Result
This chapter explains the working of the various {
members of a class. static void Main(string[] args)
{
Objectives Bike Honda = new Bike();
Honda.BikeColor = "blue";
In this chapter, you will learn to: }
 Use attributes and methods }
 Use constructors and destructors In the preceding code, the BikeColor variable is a
 Use properties public data member. Therefore, it can be accessed
outside the class.
Working with Attributes and The private Access Specifier
The private access specifier allows a class to hide its
Methods member variables and member functions from other
In a class, you need to store the data related to an object class objects and functions. Therefore, the private
in the form of attributes. You also need to divide the members of a class are not visible outside the class. The
functionalities of a class into logical units called following code shows the usage of the private access
methods. Methods are useful to perform repetitive tasks, specifier:
such as getting specific records and text. You can reuse using System;
code written in a method because it can be executed any class Car
number of times by calling the same method again and {
again. string Model;
private void Honk()
{
Defining the Scope of Attributes and Console.WriteLine("PARRP
PARRP!");
Methods }
The scope of a class member refers to the portion of the public void SetModel()
application from where the member can be read and/or {
written to. It is also known as the accessibility of a
member. Console.WriteLine("Enter
The scope of attributes and methods can be defined by the model name: ");
using access specifiers. You can use various types of Model = Console.ReadLine();
access specifiers to specify the extent of the visibility of
}
an attribute or method.
public void DisplayModel()
Types of Access Specifiers {
C# supports the following access specifiers: Console.WriteLine("The
 public model is: {0}", Model);
 private
 protected }
 internal
 protected internal }
The public Access Specifier class Display
The public access specifier allows a class to share its {
member variables and member functions with other static void Main(string[] args)
classes (within or outside the assembly in which the {
class is defined). Car Ford = new Car();
Ford.SetModel(); //Accepts the
model name }
Ford.DisplayModel(); //Displays
the model name class Result
Ford.Honk(); /*error! private {
members cannot be static void Main(string[] args)
accessed outside the class {
definition */ Bike Honda = new Bike();
Console.WriteLine Honda.BikeColor = "blue";
(Ford.Model); /*error! private }
members }
cannot be accessed outside In the preceding code, Bike and Result are two
the class definition */ classes defined within the same assembly. The
BikeColor variable is an internal member of the
} Bike class. Therefore, it can be accessed from outside
} the class. However, it cannot be accessed from the
In the preceding code, the SetModel() and classes outside the assembly in which the class, Bike is
DisplayModel() methods, defined in the Car class, contained.
can be called from the Main() method because these The protected internal Access Specifier
are public member functions. However, the Honk() The protected internal access specifier allows a
method cannot be accessed through the Ford object class to expose its member variables and member
because it is a private member function. functions to the containing class, child classes, or classes
When you do not specify any data member as public, within the same assembly. In addition, it allows access to
protected, or private, then the default access the derived classes outside the assembly.
specifier for a data member is private. In the The protected internal members are different
following example, the data member, Model is from protected members as they are accessible
private, even though it has not been explicitly within their class and sub classes, as well as, within the
specified as private: other classes in the same assembly. However, the
class Car protected members are only accessible within their
{ class and sub classes.
char Model; They are also different from internal members as
... internal members are accessible only within the
} same assembly. They are not accessible even from the
The protected Access Specifier sub classes in other assembly.
The protected access specifier allows a class to hide
its member variables and member functions from other
class objects and functions, except the subclass. The
subclass can be from the same assembly as the
protected class or from another assembly.

Protected access specifier will be discussed in


detail later in this book.
The internal Access Specifier
The internal access specifier allows a class to expose
its member variables and member functions to other
class functions and objects within the assembly in which
the member is defined. The default access specifier for a
class is internal.
The following code depicts the usage of the internal
access specifier:
using System; The following table shows the visibility of the class
members for the access specifiers in C#.
class Bike
{
internal string BikeColor;/*Since the
variable is internal, it can
be accessed outside the class
definition.*/
by using the following mechanisms:
 Value: Parameters passed by using this
mechanism are also referred to as input
parameters because data can be passed into the
method but cannot be returned out of it. This is
because any changes to the parameter that occur
within the method do not get reflected outside
the method.
 Reference: Parameters passed by using this
mechanism are also referred to as input/output
Visibility of Class Members Based on Access Specifiers
parameters because the data can be passed into
the method and can also be returned by it. This
is because a reference of the parameter is passed
to the method instead of passing the actual
value. Therefore, any changes to the parameter
that occur within the method are also reflected
outside the method.
 Output: Parameters passed by using this
mechanism are also referred to as output
parameters because the data can be extracted
from the method. Any changes made to the
parameter within a method are also reflected
outside the method. An output parameter is
declared by using the out keyword specified
before the parameter type and name.
Passing Parameters by Value
Pass by value is the default mechanism for passing
parameters to a method. The value parameter can be
defined by specifying a data type followed by a variable
Passing Information to Methods name. When a method is called, a new storage location
is created for each value parameter. When the method is
You can pass information in and out of a method. This invoked, the values passed as parameter, are copied in
can be done with the help of parameters or arguments. their respective locations in the memory.
When you define a method, you can include a list of The data types of the parameters passed to a method
parameters in the parentheses following the method must match the parameters’ data types specified in the
name. method declaration statement or they must be in a type
Declaring Parameterized Methods that can be implicitly converted.
Each parameter has a type and a name. You can declare The following statements depict the syntax used to
parameters by placing parameter declarations inside declare a value parameter:
parentheses. The syntax to declare the parameters is <access specifier> <return type>
similar to the syntax used to declare local variables. MethodName(<data type> variableName)
When more than one parameter is to be passed to a {
method, you need to separate each parameter declaration ...
with a comma within the parentheses. }
The following code snippet shows a method with two Within the method, you can write the desired code that
parameters: changes the value of the parameter. A parameter passed
void MethodWithParameters(int n, by value will have no effect on any variables outside the
string y) method call.
{ In the following code, the variable, var within the
... AddOne() method is separate from the variable,
} number in the Main() method and it can be changed
The preceding code snippet declares the in AddOne(), without affecting the value of the
methodMethodWithParameters() with two variable, number:
parameters, n and y. The first parameter is of type int, using System;
and the second parameter is of type string. class Calculator
Calling Parameterized Methods {
When a method with parameters is called, you must pass void AddOne(int var)
the parameters to the method. Parameters can be passed {
var++; Displays the value 7
} }
public static void Main() }
{
Calculator obj = new Calculator If you do not mention the ref keyword or if you
(); supply a constant or a calculated expression, the
int number = 6; compiler will reject the call to the method. You will
obj.AddOne(number); receive an error message stating that an int cannot be
Console.WriteLine(number); // converted to ref int.
Displays the value 6, not 7
Passing Parameters by Output
}
To return a value from a method you can use the
}
return statement. A return statement can be used to
Passing Parameters by Reference return only a single value. This limitation is overcome
A reference parameter is a reference to the memory by output parameter because you can pass multiple
location of a parameter. Unlike a value parameter, a output parameters to a method.
reference parameter does not create a new storage Output parameters are like reference parameters, except
location. Instead, a reference parameter represents the that they transfer data out of the method rather than into
same location in memory as the variable that is supplied it. An output parameter is a reference to a storage
in the method call. location supplied by the caller. However, the variable
You can declare a reference parameter by using the ref that is supplied for the output parameter does not need to
keyword before the data types, as shown in the following be assigned a value before the call is made, and the
example: method will assume that the parameter has not been
void ShowReference(ref int nId, ref initialized on entry.
long nCount) Output parameters are useful when you want to return
{ values from a method by means of a parameter without
... assigning an initial value to the parameter. To declare an
} output parameter, use the out keyword before the data
Theref keyword only applies to the parameter type and the variable name.
following it and not to the whole parameter list. The following code shows the use of output parameters:
Consider the following example, in which nId is passed using System;
by reference but longVar is passed by value: class OutExample
void OneRefOneVal(ref int nId, long {
longVar) static void OutDemo(out int i)
{ {
... i = 38;
} }
When invoking a method, you supply reference static void Main()
parameters by using the ref keyword, which is {
followed by a data type and a variable name. The value int num1;
supplied in the call to the method must exactly match the OutDemo(out num1);
type in the method definition. In addition, it must be a Console.WriteLine("Value is now :
variable and not a constant or a calculated expression. {0}" ,num1);
The following code is an example of calling a method }
with reference type parameters: }
using System; The following figure shows the output of the preceding
class Calculator code.
{
void AddOne(ref int var)
{
var++;
}
public static void Main()
{
Calculator obj = new Calculator
();
int number = 6;
obj.AddOne(ref number); Output of the Program
Console.WriteLine(number); // The out keyword only affects one parameter, and each
output parameter must be marked separately. When
calling a method with an output parameter, place the make the code more readable. It helps you identify the
out keyword before the variable to be passed, as shown arguments by name, instead of position.
in the following example: The name of the arguments can be passed along with
int var; their values while calling a method. The process of
OutDemo(out var); passing arguments is fairly simple. The name and value
In the body of the method being called, no initial pair of an argument is separated by a colon.
assumptions about the contents of the output parameter The method, myMethod, declared earlier, can be called
are made. It is treated like an unassigned local variable. in any of the following ways:
The output parameter must be assigned a value inside the myMethod(x:10, y:30, z:50);
method. myMethod (z:50, y:30, x:10);
myMethod (x:10, z:50);
myMethod (x:10);
In the first method call, the method is called as usual,
with the value of x as 10, y as 30, and z as 50. In the
second method call, the arguments are passed in a
different order. This can be done only with the use of
named parameters. In the third method call, only two
arguments are passed. The use of named parameters
clarifies that only the values for x and z are passed and
the value of y is omitted. In the fourth method call, only
the value of x is passed, and the remaining variables take
their default values. Thus, named arguments make the
code more readable.

The compiler will give a syntax error if the required


arguments are written after the optional ones in the method
signature.
Using Optional and Named Arguments
Named and optional arguments help in making a method
call flexible. These arguments are used mainly to make
some of the C# language features compatible with those
of other languages, such as Visual Basic.
Optional Arguments
Optional arguments allow you to omit arguments when
calling methods. This is done by assigning default values
to the arguments while defining a method. When a call is
made to the function, arguments whose values are not
passed get the default values.
For example, consider the following method declaration:
public void myMethod(int x, int y =
10, int z = 20);
In the preceding code snippet, three arguments, x,y, and
z are passed to the method. Within the signature of the
method,y is assigned the default value, 10, and z is
assigned the default value, 20. This method can be called
in any of the following ways:
myMethod (10, 30, 50); Recursion
myMethod (10, 30);
myMethod (10); You know that a method can call other methods.
In the first method call, the function will be called as However, a method can also call itself. The process of
usual with x as 10, y as 30, and z as 50. In the second calling a function from within its body is known as
method call, z has been omitted so z will get the default recursion.
value, 20. In the third method call, y and z have been The main advantage of recursion is that it is useful in
omitted so y will get the value 10, and z will get the writing clear, short, and simple programs.
value 20. To understand this concept, consider a factorial function.
A factorial function is defined as:
Named Arguments n! = 1 × 2 × 3 × 4 × ... × n
Named arguments are used with optional arguments to This same factorial function can be redefined as:
n! = (n - 1)! × n where n > 0 and 0!
= 1
This definition of n! is recursive because it refers to
itself when it uses (n - 1)!. The value of n! is 1
when n = 0, and the value of n! is defined in terms of
the smaller value of n, when n>0.
If you have to calculate 3! by using recursion, you first
define 3! in terms of 2!:
3! = (3 × 2!)
Now, you will define 2! in terms of 1!:
3! = (3 × (2 × 1!))
Now, you will define 1! in terms of 0!:
3! = (3 × (2 × (1 × 0!)))
Now, 0! is defined as 1. Therefore, the expression
becomes:
3! = (3 × (2 × (1 × 1))) The Process of Recursion
3! = (3 × (2 × 1)) The output of the preceding code is shown in the
3! = (3 × 2) following figure.
3! = 6
Consider the code for calculating the factorial of a
number:
using System;
class Number
{
public int factorial(int n)
{
int result;
if (n == 1)
return 1; Output of the Program
else The return statement is used to make a method return
{ the control immediately to the caller. Without a return
result = factorial(n - 1) * n; statement, the execution returns to the caller by default
return result; when the last statement in the method is reached.
}
}
static void Main(string[] args)
{
Number obj = new Number();
Console.WriteLine("Factorial of 4
is " +
obj.factorial(4));
}
}
In the preceding code, the factorial() method is a
recursive method. If the value provided by the user is
different than 1, this method will call itself.
The following figure shows the process of recursion of
the factorial() method.

Using Static Attributes and Methods


All member variables have a specific lifetime. For
example, if you create the temp integer variable inside a
function, the variable will be destroyed when the
function execution completes. In other words, every time
the function is called, temp will be created, initialized, before the object is created.
and then destroyed when the function exits. The following code shows an example of static
If you want a member variable to retain its value functions:
throughout the program, you can declare it as a static using System;
variable in your program. To manipulate and use the
values of staticvariables, you can also define a function public class StaticExample
as static. {
public static int i;
Static Attributes public void count()
The keyword static means that only one instance of a
{
given variable exists for a class. Static variables are used i++;
to define constants because their values can be retrieved }
by invoking the class without creating an instance of it. public static int display()
Static variables can be initialized outside the member {
function or class definition. return i;
For accessing static variables you do not need to create }
objects of a class. They can be directly accessed by using
class name. The syntax for accessing a static variable is: }
<class_name>.<variable_name> class Static
The following code is an example of static variables and {
shows the declaration and initialization of a static static int Main(string[] args)
variable: {
using System; StaticExample s = new StaticExample
public class StaticExample ();
{ s.count();
public static int ivar; //Static s.count();
variable declared s.count();
Console.WriteLine("The value of
StaticExample() variable is {0}",
{ StaticExample.display());
Console.WriteLine("Object Console.ReadLine();
created"); return 0;
}
} }
class Program }
{ The following figure shows the output of the preceding
static void Main(string[] args) code.
{
StaticExample.ivar = 1; //Static
variable Initialzed
Console.WriteLine
(StaticExample.ivar.ToString());
}
}
In the preceding code, a static variable, ivar is
initialized outside the class definition. This variable is
Output of the Program
referred directly with the help of class
name,StaticExample. We do not need to create an
object of the class to access it.
Unlike other member variables, only one copy of the
static variable exists in the memory for all the objects of
that class. Therefore, all objects share one copy of the
static variable in the memory.
Static Methods
In addition to declaring variables as static, you can
declare functions as static. Such functions can access
only static variables. In a situation where you want to
check whether an object of a class has been created, you
can make use of static functions because they exist even
22
Select the correct options that can be inserted in the code
snippet to generate the preceding output.
a. Statement 1: var = var+10;
Statement 2: var++;
b. Statement 1: var++;
Statement 2: var = var+10;
c. Statement 1: var = var+12;
Statement 2: ++var;
d. Statement 1: var+ = var
Statement 2: var = var+10;
Question 3
Predict the output of the following code:
using System;
static class demo
{
int x = 8;
public static int increment()
Let’s Practice {
x++;
Question 1 return (x);
}
public static void Main()
{

increment();
Console.WriteLine(x);
increment();
Console.WriteLine(x);
Console.ReadLine();
}
}

Activity: Swapping Two Numbers by


Using Methods with Parameters
Question 2 Problem Statement
Write a program to swap the values of two variables by
Consider the following code snippet:
using reference type parameters in a method.
void Add(ref int var)
{ Solution
//Statement 1 To write the required program, perform the following
} steps:
void Add1(int var) 1. Open Notepad.
{ 2. Write the following code in Notepad:
//Statement 2 using System;
} public class SwapNumber
public static void Main() {
{ void SwapNum(ref int a, ref int
Program p = new Program(); b)
int number = 12; {
p.Add(ref number); int temp;
Console.WriteLine(number); temp = a;
p.Add1(number); a = b;
Console.WriteLine(number); b = temp;
}
The desired output of the preceding code snippet is: }
22 static void Main(string[] args)
{
SwapNumber classobj = new
SwapNumber();
int Number1, Number2;
Console.WriteLine("Enter the
first number");

Number1 = Convert.ToInt32
(Console.ReadLine());

Console.WriteLine("Enter the Output of the Program


second number");

Number2 = Convert.ToInt32 Working with Constructors and


(Console.ReadLine());
Console.WriteLine("The value Destructors
of first number is {0}", If you want member variables to be initialized as soon as
Number1); an object is created, you can create special functions
Console.WriteLine("The value called constructors. You may also need to delete the
of second number is {0}", objects from the memory after they have been used. This
Number2); can be done in functions called destructors.
classobj.SwapNum(ref
Number1,ref Number2);
Implementing Constructors
Console.WriteLine("Now the
value of first number after Constructors are special methods that are automatically
swaping is {0}", Number1); invoked on the creation of an object. A constructor need
Console.WriteLine("Now the not be called explicitly. Consider the following code that
value of second number after shows how an initialization function, which needs to be
swapping is {0}", invoked explicitly, can be written:
Number2); using System;
} namespace Calc
} {
3. Select File→Save to save the program. The class Calculator
Save As dialog box appears. {
4. Enter SwapNumber.cs in the File name combo int number1, number2, total;
box. public void Intialize()
5. Click the Save button in the Save As dialog {
box. number1 = 10;
6. Close the SwapNumber.cs - Notepad window. number2 = 20;
7. In the Visual Studio Command Prompt window, }
change the current directory to the directory
where the program is saved. public void AddNumber()
8. Type the following command at the command {
prompt to compile the SwapNumber.cs total = number1 + number2;
program: }
csc SwapNumber.cs public void DisplayNumber()
9. Type the following command at the command {
prompt to execute the compiled program: Console.WriteLine ("The Total is :
SwapNumber.exe {0}", total);
The following figure shows the output of the executed }
program. public static void Main(string[]
args)
{
Calculator c1 = new Calculator();
c1.Intialize();
c1.AddNumber();
c1.DisplayNumber();
}
}
} Calculator()
In the preceding code, the c1 object of the {
Calculatorclass calls the Initialize() method number1 = 10;
to initialize the data members, number1 and number2 = 20;
number2. This is an explicit call to the initialization }
function. public void AddNumber()
In addition to initializing the data members, there may {
be certain code that you want to execute every time an total = number1 + number2;
}
object is created. In order to avoid making explicit calls
public void DisplayNumber()
to perform such data initialization and other tasks, OOP
{
allows you to include a special member function within
Console.WriteLine("The Total is :
the class that gets executed whenever an object of the
{0}", total);
class is created. This member function can be used to
}
perform various tasks required at the time of object
public static void Main(string[]
creation, such as initialization of data members,
args)
checking for required disk space, or creation of a new
{
file. Such a member function is called the constructor of Calculator c1 = new Calculator
the class. A constructor has the same name as the class. ();
The following code shows the use of constructors in a c1.AddNumber ();
program: c1.DisplayNumber ();
using System; }
public class Sample }
{ }
int number1;
In the preceding code, the number1 and number2
int number2;
variables are assigned with values10 and 20,
// Constructors have the same name as respectively, when the constructor is invoked by the
the class. compiler.
Sample() Static Constructors
{ Static constructors are used to initialize the static
number1 = 10; variables of a class. These constructors have an implicit
number2 = 3; private access.
} The following code snippet shows the implementation of
public static void Main(string[] the static constructor:
args) public class Class1
{ {
Sample obj=new Sample(); static int number1;
} int number2;
} static Class1()
In the preceding code, Sample class has a constructor {
named Sample()that initializes the member variables number1 = 10; /*OK. Since Number1 is
of the class as soon as an object of the class is created. a static variable in class1 */
number2 = 3; /*Error. Since Number2
Types of Constructors is a non-static variable in class1 */
The two types of constructors supported by C# are:
}
 Instance constructors }
 Static constructors
Instance Constructors
An instance constructor is called whenever an instance In practice, constructors are used to initialize data
of a class is created. These constructors are used to members and not for any input or output operations.
initialize member variables of the class. Consider the Constructors with Parameters
following code, where the preceding Calculator Constructors are generally used to initialize the variables
class is rewritten by using a constructor: of the program with values provided in the code itself.
using System; However, there may be a requirement where the
namespace Calc variables need to be initialized with user supplied values.
{ To accomplish this, you can modify the constructor to
class Calculator accept the user supplied values at runtime.
{ The following code shows the use of a constructor with
int number1, number2, total; parameters:
using System;
namespace Calc
{
class Calculator
{
int number1, number2, total;
/*Constructor defined with two
integer parameters num1 and num2.*/
Calculator(int num1, int num2)
{
number1 = num1;
number2 = num2;
}
public void AddNumber()
{
total = number1 + number2;
}
public void DisplayNumber()
{ Implementing Destructors
Console.WriteLine("The Total is :
{0}", total); Destructors are special methods that are used to release
} the instance of a class from memory. A class can have
public static void Main(string[] only one destructor. The purpose of the destructor is to
args) perform the required memory cleanup action. The
{ programmer has no control on when to call the
int var1, var2; destructor. The .NET Framework periodically checks for
Console.WriteLine("Enter Value the objects that are released from the memory. It then
1 :"); runs the destructor to destroy such objects and free the
var1=Convert.ToInt16 memory occupied by them.
(Console.ReadLine()); Declaration of Destructors
Console.WriteLine("Enter Value A destructor has the same name as its class but is
2 :"); prefixed with a ~ symbol, which represents a tilde. The
var2 = Convert.ToInt16 following code modifies the Calculator class adding
(Console.ReadLine());
a destructor in the class declaration:
Calculator C1 = new Calculator
/* This code shows the use of
(var1,var2);
destructor in the Calculator class */
C1.AddNumber();
using System;
C1.DisplayNumber();
namespace Destructors
Console.ReadLine();
{
}
class Calculator
}
{
}
static int number1, number2, total;
public void AddNumber()
The Convert.ToInt16() method converts a {
specified value to a 16-bit signed integer. total=number1+number2;
In the preceding code, the initialization values are passed Console.WriteLine("The Result is
to the member variables at the time of creating the object {0}", total);
after the values have been accepted from the user. While
accepting the values from the user, the }
Convert.ToInt16() method converts the string Calculator() //Constructor
{
returned by the Console.ReadLine() method to a
number1=20;
16-bit signed integer. number2=30;
The following statement invokes the constructor and total=0;
passes the initialization values for the num1 and num2 Console.WriteLine ("Constructor
variables: Invoked");
Calculator C1 = new Calculator }
(var1,var2); Calculator() //Destructor
{
Console.WriteLine ("Destructor {
Invoked "); TestCalculator()
} {
Console.WriteLine("Constructor
static void Main(string[] args) Invoked");
{ }
Calculator c1=new Calculator(); TestCalculator()
c1.AddNumber(); {
} Console.WriteLine("Destructor
} Invoked");
} }
In the preceding code, the .NET Framework public static void Main(string[]
automatically runs the destructor to destroy objects in args)
the memory and displays the message Destructor {
Invoked. The following figure shows the output of the Console.WriteLine("Main()
preceding code. Begins");
TestCalculator calc1 = new
TestCalculator();
{
Console.WriteLine("Inner Block
Begins ");
TestCalculator calc2 = new
TestCalculator();
Console.WriteLine("Inner Block
Ends");
}
Output of the Program Console.WriteLine("Main()
When you do not create an explicit destructor in your ends");
program, the garbage collector releases the memory for
}
you.
}
}

The following figure shows the output of the preceding


code.

Output of the Program


Lifecycle of an Object In the preceding output:
 The calc1 object has function scope.
The following code is an example to show the order in Therefore, its constructor is executed after the
which constructors and destructors are called by the execution of Main() begins.
compiler:
 The calc2 object has block scope. Therefore,
using System;
its constructor is executed after the execution of
//Life Cycle of an Object
the inner block begins.
namespace Objects
{ The destructor of all objects is invoked when garbage
class TestCalculator collector is invoked.
derived classes. This destructor is called after the last
reference to an object is released from the memory.
The .NET Framework automatically runs the
Finalize() destructor to destroy the objects in the
memory. However, it is important to remember that the
Finalize() destructor may not execute immediately
when an object loses scope.
This is because the compiler calls the Finalize()
destructor by using a system called reference tracing
garbage collection. In reference-tracing garbage
collection, the compiler periodically checks for objects
that are not used by the application. When such an object
is found, the Finalize() destructor is called
automatically and the garbage collector of the compiler
releases the object from the memory.
The Dispose() method is called to release a resource,
Garbage Collection such as a database connection, as soon as the object
Garbage collection is a process that automatically frees using such a resource is no longer in use. Unlike the
the memory of objects that are no more in use. The Finalize() destructor, the Dispose() method is
decision to invoke the destructor is made by the garbage not called automatically, and you must explicitly call it
collector. The destructor is not necessarily invoked if an in your program when an object is no longer needed. The
object by itself loses scope at the end of the Main() IDisposable interface contains the Dispose()
method. Therefore, in C#, you cannot determine when method. Therefore, to call the Dispose() method, the
the destructor is called. Garbage collector identifies the class must implement the IDisposable interface.
objects that are no more referenced in the program and
releases the memory allocated to them.
An interface defines properties, methods, and events
to group the related functionalities that can belong to any
class. Interfaces will be explained in subsequent chapters.

In C#, you cannot destroy an object explicitly in code.


The garbage collector can only destroy the objects for
the programmers. The process of garbage collection
happens automatically. The garbage collector ensures
that:
 Objects get destroyed. However, it does not Activity: Counting the Number of
specify when the object shall be destroyed. Objects of a Class by Using Static
 Only unused objects are destroyed. An object is
never destroyed if it holds the reference of Functions
another object.
C# provides special methods namely, Finalize() and
Problem Statement
John, a software developer in Zed Axis Technologies,
Dispose(), which are used to release the instance of a
needs to track the number of objects of a class that are
class from memory.
created. For the same, he has been asked to create a class
The Finalize() destructor is a special method that is
named ObjectCount. Help John to create a program
called from the class to which it belongs or from the
containing the ObjectCount class.
Solution
To create the required program, John needs to perform
the following steps:
1. Open Notepad.
2. Write the following code in Notepad:
using System;
public class ObjectCount
{ Output of the Program
public static int count;

public ObjectCount() Working with Properties


{
count++; In the object-orientated programming approach, data
} hiding is a fundamental concept. By the use of access
public int display() modifiers, it is possible to control the accessibility of the
{ class members.
return count; It is a good programming practice to declare an attribute
} as private and provide a set of public set and get methods
to access that attribute. This helps in preventing the
} access of attributes directly from outside the class. C#
class Static provides a built-in mechanism, called properties, to
{ implement this concept.
static int Main(string[] args)
{
ObjectCount obj1 = new Defining Properties
ObjectCount();
Properties are a natural extension of attributes. They help
ObjectCount obj2 = new
a class provide a public interface for getting and setting
ObjectCount();
ObjectCount obj3 = new values for private attributes, while hiding the
ObjectCount(); implementation.
A property, generally, has a private data member,
Console.WriteLine("Number of accompanied by accessor functions, and is accessed as a
objects created are {0}", field of a class.
obj3.display()); A property is usually declared private in a class and a set
of public set and get accessor methods provide access to
Console.ReadLine(); the property. The get and set methods are like any other
return 0; method. They can perform any program logic, throw
} exceptions, be overridden, and be declared with any
} modifier.
3. Select File→Save to save the program. The A major advantage of properties is that you can run some
Save As dialog box appears. lines of code at the time of assigning value to a variable.
4. TypeObjectCount.cs in the File name combo For example, if you want to check the range of a value
box. before assigning it to a variable, you can use a property.
5. Click the Save button in the Save As dialog The general syntax of declaring a property is:
box. <acces_modifier> <return_type>
6. Close the ObjectCount.cs - Notepad window. <property_name>
7. In the Visual Studio Command Prompt window, {
change the current directory to the directory get //get accessor method
where the program is saved. {
8. Type the following command at the command }
prompt to compile the ObjectCount.cs set //set accessor method
program: {
csc ObjectCount.cs }
9. Type the following command at the command }
prompt to execute the compiled program: In the preceding syntax, access_modifier can be
ObjectCount.exe private,public,protected, orinternal; and
The following figure displays the output of the executed the return_type can be any valid C# type.
program. The following code shows the use of properties:
using System;
class MyClass Like attributes and methods, properties can also be
{ static. Static properties can access only static
private int x; variables. Only one copy of a static property is
public int X maintained for all the objects of a class.
{ The following code depicts an example of static
get properties:
{ using System;
return x; class MyClass
} {
set private static int x;
{ public static int X
x = value; /*value is a {
variable present by default in the get
set accessor*/ {
} return x;
} }
} set
class MyMain {
{ x = value;
public static void Main() }
{ }
MyClass mc = new MyClass(); }
mc.X = 10; //set method is called
int xVal = mc.X; //get method is class MyClient
called {
Console.WriteLine(xVal); //Displays public static void Main()
10 {
} MyClass.X = 10;
} int xVal = MyClass.X;
Similar to other class members, you can access a Console.WriteLine(xVal);//Displays
property through an object. In the preceding code, when 10
you assign the value 10 to the property, the set method }
is called automatically, and the value, 10, is assigned to }
the attribute, x. Later, when you access the value of the In the preceding code, the static variable, x, is accessed
property, the get function is called automatically, which through a static property.
returns the value of the attribute, x.
A property should have at least one accessor, either set
orget. Theset accessor has a variable in it called
value, which gets created automatically by the
compiler. You cannot declare a variable with the name,
value, inside the set accessor.

Let’s Practice
Consider the following code snippet:
using System;
class myClient
{  Named arguments help you to identify the
public static void Main() arguments by name, instead of by position.
{  The keyword static means that only one
myClass.X = 10; instance of a given variable exists for a class.
int xVal = myClass.X;  Static variables retain their value throughout the
// Statement 1 program.
}  Static functions are used to manipulate and use
} the static variables.
class myClass  Constructors are member functions of a class
{ and are invoked when an instance of the class to
private static int x; which they belong is created.
public static int X  A constructor has the same name as its class.
{  Destructors are used to release the instance of a
// Statement 2 class from memory.
get  A destructor has the same name as its class, but
{ it is prefixed with a  (tilde).
return x;  Constructors are special methods that allow
} control over the initialization of objects.
}
 Destructors are special methods that are used to
}
release the instance of a class from memory.
 Garbage collection is a process that
You need to modify the preceding code snippet to give automatically frees the memory of objects that
the following output: is no more in use.
10  The Finalize() destructor is called after the
last reference to an object is released from the
Select the correct options that can be inserted in the memory.
preceding code snippet to generate the desired output.  The Dispose() method is called to release a
a. Statement 1: Console.WriteLine
resource, such as a database connection, when
(xVal);
the object using such a resource is no longer in
Statement 2: set{x = value;}
use.
b. Statement 1: set{x = value};
 A property generally has a private data member
Statement 2: Console.WriteLine
accompanied by accessor functions and is
(xVal);
accessed as a field of a class.
c. Statement 1: get{x = value};
 Like attributes and methods, properties can also
Statement 2: Console.Write
be static.
(xVal);
d. Statement 1: set{return x};
Statement 2: Console.Write
(xVal); Exercises
Exercise 1
Write a program that should accept two numbers from
Summary the users and perform the following mathematical
In this chapter, you learned that: operations:
 C# supports five types of access specifiers:  Addition
public, private, protected,  Subtraction
internal, and protected internal.  Multiplication
 Parameters allow information to be passed into  Division
and out of a method. When you define a In case of division, an error message should be displayed
method, you can include a list of parameters in if the second number is zero.
parentheses.
 Parameters can be passed in three ways: pass by
value, pass by reference, pass by output.
 Pass by value is the default mechanism for
passing parameters in C#. Exercise 2
 The return statement is used to make a Write a program to identify the largest of three numbers
method return immediately to the caller. entered by a user. Create this program by using methods.
 Optional arguments allow omitting arguments
when calling methods.
public void Display(int number)
{
Console.WriteLine(number);

Exercise 3 }
Write a program to calculate the factorial of the number Calculate()
entered by a user. Create this program by using static {
functions and static variables. number1++;
Hint: The limit of users input should be 1-20. Display(number1);
}
static Calculate()
{
number1 = 10;
Exercise 4 number1++;
Predict the output of the following program: }
using System; static void Main(string[] args)
namespace Square_Number {
{ Calculate Cal1 = new Calculate();
Calculate Cal2 = new Calculate();
class CalculateSquare Console.ReadLine();
{ }
int number; }
public void Square(int number) }
{
Console.WriteLine("The number is:
{0}",number);
number *= number;
Console.WriteLine("Square of 10 Exercise 6
is: {0}", number); Write a program to maintain the details of the stock of a
} shop under the item categories, Women, Men, Girls,
CalculateSquare() Boys, and Babies. Accept item category from the user. In
{ addition, accept item name, number of units, and unit
number = 10; price. Define all the attributes as properties. Finally,
Square(number); display all the details.
}

static void Main(string[] args)


{
CalculateSquare cal = new
CalculateSquare();
Console.ReadLine(); Reference Reading
}
}
Working with Attributes and Methods
}
Reference Reading: Books Reference Reading: URLs
Simon Robinson, http://www.codeguru.com/
Professional C# csharp/.net/net_general/
assemblies/article.php/
Exercise 5 c7009
Predict the output of the following program:
using System; Working with Constructors and
namespace CalculateNumber
{
Destructors

class Calculate Reference Reading: Books Reference Reading: URLs


{ Simon Robinson, http://www.c-
Professional C# sharpcorner.com/
static int number1; UploadFile/neerajsaluja/
Constructors
InCSharp11152005233222
PM/
ConstructorsInCSharp.aspx

Working with Properties

Reference Reading: Books Reference Reading: URLs


Herbert Schildt, C# 3.0: http://
The Complete Reference www.csharphelp.com/2007/
03/objects-classes-in-c/
Chapter 4
Creating Value Types and Reference
Types
Value Type and Reference Type Variables
The variables in a program are allocated memory in the In the preceding figure, a value type variable named
system at run time. In C#, variables are referred in two Num1 holds the value 5. The reference type variable
ways, by value and by reference. Value type variables named Car holds the value to a memory location where
contain data, whereas reference type variables hold the the value, Rolls Royce Phantom, is stored.
reference to the memory location where data is stored. To understand value type referencing, consider an
This chapter explains how C# manages memory for its example, where you declare a variable named Num1 as
variables. It also explains the implementation of value an int and assign the value 50 to it. If you declare
types, such as structures and enumerations. Further, the another variable Num2 as an int, and assign Num1 to
chapter describes how to implement reference types,
Num2, Num2 will contain the same value as Num1.
such as arrays and collections, in C#.
However, both the variables contain different copies of
Objectives the value 50. If you modify the value in Num1, the value
in Num2 does not change.
In this chapter, you will learn to: The following code snippet is an example of value type
 Describe memory allocation variables:
 Use structures int Num1=50; // declare and
 Use enumerations initialize Num1
 Implement arrays int Num2=Num1; // Num2 contains the
 Implement indexers copy of the data in Num1
 Use collections Num1++; // incrementing Num1 will
 Implement generics have no effect on Num2
The following figure shows how the memory is allocated
to the value type variables in the preceding example.
Describing Memory Allocation
The memory allocated to variables is referred to in two
ways, by value and by reference. The built-in data types
such as int, char, and float are value types. When
you declare an int variable, the compiler allocates a
block of memory to hold an integer value. Consider the
following statement:
int Num1=50;
The preceding statement allocates memory for the Num1
variable that holds the value 50.
Reference types, such as classes are handled differently
by the compiler. When you declare a class variable, the
compiler does not allocate a block of memory to hold a
class. Instead, it allocates a piece of memory that can Memory Allocated for Value Type Variables
store the reference to another block of memory
containing the class. The memory for the class object is
allocated when the new keyword is used to create an All value types are created on the stack. Stack
object. memory is organized like a stack of books piled on a rack.
Value types contain data, whereas, reference types hold To understand reference types, consider a class named
the reference to the location where data is stored. Car. If an object named BMW of the Car class is
Therefore, value types are known as direct types and initialized with another object named Ford of the same
reference types are known as indirect types. The class, both Ford and BMW will refer to the same
following figure shows a value type and a reference type location.
variable. The following code is an example of reference type
variables:
using System;
namespace Ref_Type
{
class class1
{ Let’s Practice
static void Main (string[] args)
{ Predict the output of the following code:
Car Ford = new Car (); using System;
Ford.Model = 10; class class1{
Car BMW = Ford; static void Main (string[] args){
BMW.Display_Model (); Car Ford = new Car (22);
Ford.Display_Model (); Ford.Model = 10;
} Car BMW = Ford;
} BMW.Display_Model ();
class Car Ford.Display_Model ();
{ }
public int Model; }
public void Display_Model ()
{ class Car{
Console.WriteLine (Model); public int Model;
} public Car(int a){
} Model = a;}
} public void Display_Model(){
Console.WriteLine(Model);
The following figure shows how the memory is allocated
}
to the reference type variables in the preceding code.
}

Using Structures
A structure is a value type data type. When you want a
single variable to hold related data of various data types,
you can create a structure. To create a structure you need
to use the struct keyword.
For example, if you want to maintain bill details, such as
bill_No, ord_Dt, custName, product, cost,
Memory Allocation for Reference Type Variables and due_Amt, in a single variable, you can declare a
structure. The following code snippet shows how you
All reference types are created on the heap. Heap can create a structure:
memory is like books arranged next to each other in rows. struct Bill_Details
{ public string bill_No; // Bill
In addition to the built-in data types such as int Number
andfloat, there are other value types like, structures public string ord_Dt; // Order Date
and enumerations, which are user-defined data types. public string custName;// Customer
Similarly, there are various reference types like arrays name
and collections. public string product;// Product Name
public double cost;// Cost of the
product
public double due_Amt;// Total amount
due
};
Like classes, structures contain data members which are
defined within the declaration of the structure. However,
structures differ from classes and the differences are:
 Structures are value types and get stored in a
stack.
 Structures do not support inheritance.
 Structures cannot have default constructor.

You will learn about constructors in subsequent


chapters.
The following code uses the Bill_Details structure: Output of the Program
using System;
namespace Bills
{
public struct Bill_Details
{
public string bill_No;
public string ord_Dt;
public string custName;
public string product;
public double cost;
public double advance_Amt;
public double due_Amt;
}

class TestStructure
{
public static void Main(string[]
args)
{
Bill_Details billObj = new Let’s Practice
Bill_Details();
billObj.bill_No = "A101"; Write a program that accepts the following student
billObj.ord_Dt = "10/10/06"; details and displays it by implementing structures:
billObj.custName = "Joe";  Name of the student
billObj.product = "Petrol";  Course in which the student wants to get
billObj.cost = 100; enrolled
billObj.advance_Amt = 50;  Student Id and Registration Id of the student
billObj.due_Amt = 50;
Console.Clear();
Console.WriteLine("Bill Number is Using Enumerations
{0}", billObj.bill_No); Enumeration is a value type data type, which means that
Console.WriteLine("Order Date is enumeration contains its own values and cannot inherit
{0}", billObj.ord_Dt); or pass inheritance. Enumerator allows you to assign
Console.WriteLine("Customer Name is symbolic names to integral constants. For example, you
{0}", billObj.custName); may want to write a program to display weekdays in a
Console.WriteLine("Product is {0}", program. You could use the integers 0, 1, 2, and 3 to
billObj.product); represent Monday, Tuesday, Wednesday and Thursday,
Console.WriteLine("Cost is {0}", respectively. This representation would work, but it has a
billObj.cost); problem. It is not convenient. If the integer value 0 is
Console.WriteLine("Advance Amount
used in code, it would not be obvious that 0 represents
is {0}", billObj.advance_Amt);
Monday. To overcome such a problem, you can use
Console.WriteLine("Due Amount is
enumeration. To create an enumeration, you can use the
{0}", billObj.due_Amt);
enum keyword.
Console.ReadLine();
}
}
}
Declaring an Enumeration
The following figure shows the output of the preceding To declare an enumeration type called Days, where the
code. values are restricted to the symbolic names of the
weekdays, use the following code snippet:
enum Days {Mon, Tue, Wed, Thu, Fri,
Sat, Sun };
The names of days must appear within braces and must
be separated by commas. The enumeration type gives a
numeric value to every element. By default, the
sequence of values starts from 0 for the first element and
increments by 1 for every subsequent value.
Implementing Enumerations Let’s Practice
After declaring an enumeration type, you can use it in Predict the output of the following code:
the same manner as any other data type, as shown in the using System;
following code: class Enummeration_Demo
using System; {
namespace EnumDays enum MeetingImportance
{ {
class EnumTest Trivial,
{ Regular,
enum Days {Mon, Tue, Wed, Thu, Fri, Critical,
Sat, Sun }; }
static void Main(string[] args) {
int First_Day = (int)Days.Mon; public static void Main()
int Last_Day = (int)Days.Sun; {
Console.Clear(); MeetingImportance meet =
Console.WriteLine("Mon = {0}", MeetingImportance.Critical;
First_Day); int value = (int)
Console.WriteLine("Sun = {0}", MeetingImportance.Critical;
Last_Day);
Console.ReadLine(); if (meet ==
} MeetingImportance.Trivial)
} {
} Console.WriteLine("Trivial:" +
In the preceding code, Days has been declared as value);
anenum data type. This enum has symbolic names, }
which appear within braces. In the class EnumTest, the else if (meet ==
Main() method displays the values of enum Days. The MeetingImportance.Regular)
local variables First_Day and Last_Day hold the {
Console.WriteLine("Regular:" +
value of enum and display the values for Mon and Sun
value);
as an output. The following figure shows the output of
}
the preceding code.
else if (meet ==
MeetingImportance.Critical)
{
Console.WriteLine("Critical:" +
value);
}
Console.ReadLine();
}
Output of the Program
}
Implementing Arrays
An array is a collection of values of the same data type.
For example, you can create an array that stores 10
integer type values. The variables in an array are known
as array elements. Array elements are accessed by using
a single name and an index number representing the
position of the element within the array. Array is a
reference type data type. The following figure shows the
array structure in the system’s memory.

The Array Structure Initializing and Assigning Values to


Array
Declaring an Array Declaring an array variable does not initialize the array
in the memory. You can assign values to the array
elements once the array is initialized.
Initializing Array
Array is a reference type, and therefore, you need to use
the new keyword to create an instance of the array. The
size of the array is specified while it is initialized. The
following code snippet is an example of array
initialization:
int[] Score; // Array declaration
Score = new int[10]; //Array Instance
The preceding two statements can be combined into a
single statement, and written as:
int[] Score = new int[10];
In C#, the array index (subscript) always starts with zero.
Therefore, the preceding statement creates an array of
integers named, Score, containing 10 elements with the
index of elements ranging from 0 to 9. The following
An array needs to be declared before it can be used in a figure shows the Score array with index number of
program. You can declare an array by using the each element in the array.
following syntax:
datatype[] Arrayname;
The preceding syntax for declaring an array involves
various components, which are:
 datatype: Is used to specify the data type for
the elements, which will be stored in the array.
 []: Is used to specify the size of the array and
is also referred to as its rank. The Score Array
 Arrayname: Is used to specify the name of the Assigning Values to the Array
array by using which the elements of the array You can assign values to each element of the array by
will be initialized and manipulated. using the index number, which is also called the array
The following code snippet is an example of the array subscript of the element. For example, to assign the
declaration: value 5 to the first element of the array, you can use the
int[] Score; following code snippet:
int[] Score = new int[9];
Score[0] = 5;
You can also assign values to the array at the time of
declaration. However, in case of such explicit MADAM, EYE, CIVIC, LEVEL, RACECAR.
initialization, you cannot specify the size of the array, as //Code to check a palindrome character
shown in the following code snippet: array
int[] Score = {5, 10, 15}; using System;
The C# compiler implicitly initializes each array element namespace ManipulateArray
to a default value depending on the array type. For {
example, an integer array would be initialized to 0 by the class Palindrome
compiler. {
You can also create and initialize an integer array static void Main(string[] args)
containing a specific number of elements, as shown in {
the following code snippet: char[] Str = new char[10];
int[] Score = new int[10] {0, 1, 2, //Enter a palindrome string
3, 4, 5, 6, 7, 8, 9}; Console.WriteLine("Enter a
In the preceding code snippet, the curly braces ({}) are Palindrome string (Max 10 Char):");
used to initialize the array elements. //Accepting a string and
Further, if you declare the array, you can omit the size of converting in to Char array
the array, as shown in the following code snippet: Str=Console.ReadLine
int[] Score = new int[] {0, 1, 2, 3, ().ToCharArray();
4, 5, 6, 7, 8, 9}; //Calling the CheckPalidrome
method
Copying an Array Console.WriteLine
When you copy an array to another array, both the (CheckPalindrome(Str));
source and the target refer to the same array instance in }
the memory. The following code snippet shows how an private static bool CheckPalindrome
array can be copied to another array: (char[] myString)
int[] Source = new int[10] {0, 1, 2, {
3, 4}; int startChar;
int[] Target= Source; int lastChar;
In the preceding code snippet, two array variables, startChar = 0;
namely Source and Target, are created. These
variables point to the same location in the memory. /*using Length method to calculate
the total characters in the array*/
lastChar = myString.Length - 1;

//Executing the loop till the last


character in the array
while (startChar < lastChar)
{
//Checking if the arrays from both
the ends are equal
if (myString[startChar] ==
myString[lastChar])
{
startChar++;
lastChar--;
}
else
{
return false;
}
Manipulating Array Elements }
return true;
When an array is initialized, you can access the element }
values and manipulate them. The following code is an }
example of array manipulation and checks whether the }
input by a user is a palindrome or not:

The ToCharArray() method converts the string


A palindrome is a word, phrase, or number that can values to a char[] array.
be read the same way in either direction. For example,
In the preceding code, a character array, Str, is declared The following statements depict the syntax of the
and initialized. The value in the array is entered by the foreach statement:
user. The ReadLine() method reads the input from foreach(type identifier in
the user in the string datatype. Therefore, to store in expression)
user input in Str character array, the ToCharArray statement-block
() method is used. The Length() method is used to The following code includes a set of instructions to
calculate the length of the array myString and the declare an array called Numbers, process an array with
same is stored in a variable named lastChar. While the foreach statement, and write the values to the
storing the length, the value is decreased by 1 because console:
the subscript index number of the array starts with 0. using System;
The following figure shows the startChar and namespace ForEach
{
lastChar variables pointing to the first and the last
class ForEachExample
character in the myString character array.
{
static void Main (string[] args)
{
int [] Numbers = { 4, 3, 2, 1, 0,
-1, -2, 9, 5 };
Console.WriteLine("The Content of
the Array is:");
foreach (int K in Numbers)
{
Console.Write("{0} \t",K);
}
Console.ReadLine();
The myString Array
}
In the preceding figure, the myString character array
}
contains the value, racecar, entered by the user. The }
startChar variable contains the value, R, which is the
The following figure shows the output of the preceding
first character in the array. The lastChar variable code.
contains the value, R, which is the last character in the
array.
The following figure shows the output of the preceding
code.

Output of the Program


You can also pass arrays as parameters to a method.
Param Arrays
While declaring a method if you are not sure about the
number of arguments to be passed as a parameter, you
Output of the Program
can use the param array.
The while loop is used to repeat the statements for
The following code is an example of using the param
comparing the characters in an array. The == operator is array in a method’s parameter list:
used to check for the equality of characters in the array. using System;
Many other loops are used for manipulating arrays. namespace ParamArrays
However, the foreach loop is specifically used for {
manipulating arrays.
foreach Loop public class ParamExample
A statement that iterates through an array and executes {
the same set of instructions on each element is very public int Adding_ArrayElement(params
common. You can use any looping construct to iterate int[] List)
through an array, but the foreach statement interprets {
the common looping process by removing the need for int Total = 0;
you to check the array size. foreach ( int I in List )
{ row. In addition to single dimensional arrays, you can
Total += I; declare multidimensional arrays, which store data in
} more than one row (dimension).
return Total; The following figure compares a single dimensional
} array with a multidimensional array.
}
class Tester
{
static void Main(string[] args)
{
ParamExample Param_Exam = new
ParamExample();
int Total =
Param_Exam.Adding_ArrayElement
(1,2,3,4,5,6,7);
Console.WriteLine( "The Result is
{0}",Total ); Single and Multidimensional Arrays
} The following code is an example of a multidimensional
} array:
} using System;
The following figure shows the output of the preceding
code. namespace MultiDimArray
{
class MultiArrayExample
{
static void Main(string[] args)
{
int sum=0;
int rowSum;
int[,] mArray = new int[2, 4]{
Output of the Program {2,2,2,2},
{3,3,3,3}
In the list of parameters for a method, param array };
should be the last parameter. for (int row=0; row <2; row++)
{
rowSum = 0;
for (int col=0; col < 4; col++)
{
Console.Write("{0}\t",mArray
[row,col]);
rowSum=rowSum+mArray[row, col];

}
sum = sum + rowSum;
Console.Write(" = {0}", rowSum);
Console.WriteLine();

}
Console.WriteLine("The sum of the
array is:{0}", sum);
Console.ReadLine();
}
}
}
Multidimensional Arrays The following figure shows the output of the preceding
The rank value of the array is also known as the code.
dimension of the array. The arrays declared and used in
the preceding examples are single dimensional arrays. In
a single dimensional array, values are stored in a single
Output of the Program
The Array Class
The Array class is the base class for all the arrays in
C#. The Array class is defined in the System
namespace and provides various properties and methods
to work with arrays.
Properties of the Array Class
The following table explains some of the commonly
used properties of the Array class.
Let’s Practice
Property Explanation Predict the output of the following code:
Length Returns the total number of using System;
items in all the dimensions class ArrayExample{
of an array public static void Main(string[]
Rank Returns the rank (number args) {
of dimensions) of an array String[] src = new String[] {
IsFixedSize Return a value indicating "Marigold", "Rose", "Lotus",
whether an array has a "Larkspur"};
fixed size or not String[] Info = src;
IsReadOnly Returns a value indicating foreach(string k in Info){
whether an array is read- Console.WriteLine(k[2]);
only or not }}}

Commonly Used Array Class Properties


Methods of the Array Class Activity: Word Puzzle
The following table explains some of the commonly
Problem Statement
used methods of the Array class.
Write a program to create a game that implements the
following features:
Method Explanation 1. Display the following word:
Sort Performs the sort operation MASTER
on an array passed to it as 2. Ask the user to create multiple words from the
a parameter letters of the given word.
Clear Removes all items of an 3. Display the basic instructions to play the game.
array and sets a range of 4. The program should display “Correct” and
items in the array to 0 increase the score of the user by 1, if the user
GetLength Returns the number of enters a correct word.
items in an array 5. The program should display “You have already
GetValue Returns the value of the entered the word: ####”, if the user enters a
specified item in an array word repetitively.
IndexOf Returns the index of the
first occurrence of a value #### stands for the word entered by the
in a one-dimensional Array user.
or in a portion of the array 6. The program should display “Incorrect”, if the
user enters a word that is not valid.
Commonly Used Array Class Methods 7. The program should display the final score, if
the user enters the word “QUIT”.
Solution
using System; c = true;
using System.Collections.Generic; }
using System.Text; }

namespace WordPuzzle if (c == true)


{ {
class Program Console.WriteLine("You have
{ already entered: " + a);

string[] result = new string[] }


{ "ATE","EAT", "ART", "MAT", "MET", bool d = false;
"RAT", "SAT", "SET", "RAM", "SAME", foreach (string element in
"STARE", "RATE", "MATE", "STEM", p.result)// validate the word entered
"TERM", "EAST", "REST", "TEAR", by user is in the given array or not.
"MARE", "SEAT", "TEAM", "TRAM", {
"STREAM", "MATS", "SEAM", "MEAT", if (a == element)
"MART","MASTER" }; {
string[] compare = new string[35];
int score = 0; if (c == false)
public void displayDetails() {
{ p.score++;
Console.WriteLine("Welcome to the for (int i = 0; i <
game of WORD PUZZLE\n"); p.compare.Length; i++)
Console.BackgroundColor = {
ConsoleColor.Blue;
Console.WriteLine("Create words if ((p.compare[i] == "" ||
of three or more letters from the p.compare[i] == null))
word:\tM A S T E R"); {
Console.BackgroundColor =
ConsoleColor.Black; p.compare[i] = a;
Console.WriteLine Console.WriteLine
("\nInstructions:\n1. Please enter ("Correct");
the words in uppercase only. \n2. break;
Every correct word will add 1 point }
to your score. \n3. In order to quit }
the game, type 'QUIT'."); }
d = true;
} }

static void Main(string[] args) }


{
bool b = true;
Program p = new Program(); if (a == "QUIT") // If user
p.displayDetails(); enters quit then show the final
Console.WriteLine("Please enter result and quit.
the words."); {
do
{ b = false;
Console.ForegroundColor =
string a; ConsoleColor.Yellow;
a = Console.ReadLine(); Console.WriteLine("Your final
bool c = false; score is:" + p.score);
for (int i = 0; i <
p.compare.Length; i++)// To verify break;
that user don't entered any word more }
than once. if (d == false)
{ {
if (a == p.compare[i]) Console.WriteLine("Incorrect");
{ }
} while (b); {
} return name[index];
}} }
The output is displayed, as shown in the following set
figure. {
name[index] = value;
}
}
}

class MyMain
{
public static void Main()
{
The Output myIndexer ind = new myIndexer();
ind[0] = "John"; //calls the setter
method
Implementing Indexers ind[1] = "Sam";
ind[2] = "Maria";
Fast access to data is an important aspect that needs to be ind[3] = "Paul";
considered while developing software. You can index the ind[4] = "Rachel";
data for quick access. In C#, you can index the instance Console.WriteLine("{0},{1},{2},{3},
of a class or a structure as an array, which is useful for {4}",ind[0],ind[1],ind[2], ind[3],ind
iterating or data binding operations. This can be [4]); //calls the getter method
achieved by the use of indexers. }
}
The following figure shows the output of the preceding
Defining Indexers code.
Indexers are usually known as smart arrays in C#. They
help you to use an object as an array. Indexers are
normally used while creating a collection class.
Similar to properties, indexers have a set of setter and
getter methods, called accessors. The syntax for defining
an indexer is:
<modifier> <return type> this
[argument list]
{
get Output of the Program
{ Consider the following statement that appears in the
// code preceding code:
} ind[0] = "John";
set In the preceding statement, the setter method is
{ automatically called, and the index value, 0 is passed as
// code the parameter to the this method. The value, John, is
} then assigned to the 0th element of the array.
} Similarly, the corresponding values of all the indexes are
In the declaration of an indexer, the this keyword is set.
used to refer to an instance of the current class. Now, consider the following statement that appears in
Consider the following code: the preceding code:
using System; Console.WriteLine("{0},{1},{2},{3},
using System.Collections; {4}",ind[0],ind[1],ind[2], ind[3],ind
[4]);
class myIndexer When a reference to an array element is made, the get
{ method is automatically called, and the index value is
private string []name = new string passed as the parameter to the this method, which
[5]; returns the value that was assigned to that array element
public string this [int index] earlier in the set method.
{ The set accessor has a variable available in it called
get
value, which gets created automatically by the compiler.
We can’t declare any variable with the name, value,
inside the set accessor.
Indexers help in reducing the complexity of
programs.The indexer notation not only makes the
program more understandable, it also makes the class
and its purpose more clear for other developers to
understand.
Consider the following code:
using System;
using System.Collections;

class RecordTemp
{
private float[] temps = new float
[10];
public float this[int index]
{
get Comparing Indexers and Properties
{
Indexers are similar to properties. Both use a set of setter
return temps[index];
and getter methods to access the attributes of a class.
}
set However, the use of indexers and properties is quite
{ different. Some of the differences between indexers and
temps[index] = value; properties are listed in the following table.
}
} Indexer Property
} Indexers do not have a Properties are identified by
name. They are identified their name.
class MyMain by their signature.
{ Indexers are accessed Properties are accessed
public static void Main() similar to the way arrays similar to the way an
{ are accessed. attribute is accessed.
RecordTemp tr = new RecordTemp(); Indexers cannot be static. Properties can be static.
tr[0] = 10.1f;//calls the setter A get accessor of an A get accessor of a
method indexer has the same property has no
Console.WriteLine("{0}", tr[0]);//
parameter list as the parameters.
calls the getter method
indexer.
}
} A set accessor of an A set accessor of a
In the preceding code, a class named RecordTemp indexer has the same property contains the
parameter list as the implicit value parameter.
stores the temperature recorded at 10 different times in a
indexer. In addition, it has
day. The class contains an array named temps to
another parameter called
represent the temperatures. By implementing an indexer
value.
in this class, a user can directly access the temperatures
from the RecordTemp instance named tr as float
Differences Between Indexer and Property
temp = tr[0] instead of as float temp =
tr.temps[0].
The preceding problems can be avoided by using a
collection. A collection is similar to an array. However, it
has a lot of code wrapped around it to manage the data
that it contains. In addition, the size of a collection can
be expanded as per requirement. In C#, collections are
implemented by using special classes declared in the
System.Collections namespace and its sub-
namespaces.
Unlike an array, a collection can store data of different
data types. The following figure illustrates a collection
containing both string and integer data.

A Collection Containing String and Integer Data


Let’s Practice Elements are stored in a collection as objects. For
example, when you assign an integer value to an element
Consider the following code snippet: of a collection, the value is automatically converted to an
using System;
object and stored in the collection. However, when you
class myIndexer{
try to retrieve a value stored in a collection into a
private string []name = new string
variable, the variable needs to be of the same data type
[5];
as the value being retrieved; otherwise the program
// code to implement indexers
produces an error. This limitation of collections can be
}
overcome by using strongly typed collections, which can
}
be created using the concept of generics.
class MyMain{
public static void Main(string[]
args){ Generics will be covered later in this book.
myIndexer ind = new myIndexer(); The following table shows the various classes of the
ind[0] = "New"; System.Collection namespace.
ind[1] = "Old";
Console.WriteLine("{0},{1}", ind
[0], ind[1]);
}}
Complete the preceding code snippet to print the output
as: New,Old

Using Collections
You have learnt how to use arrays to efficiently store and
manipulate similar type of data. However, the following
limitations are associated with the use of arrays:
 You have to define the size of an array at the
time of declaration.
 You have to write code to perform standard
operations, such as sorting, on an array.
Let us consider an example. Suppose you want to store
the names of five employees working in an organization.
You can declare an array to store the names of the five
employees, by using the following statement:
Various Collection Classes
string [5] employees;
employees=new string[5];
Here, the size of the array is fixed to five elements. In
addition, you have to write code to perform standard
operations such as adding elements to the array or
sorting the array.
array list
Reverse() Reverses the element in the
array list

Common Methods of the ArrayList Class

You cannot use the Remove() method in a


foreach loop that iterates through an ArrayList class.
Consider the following code:
using System;
using System.Collections;
public class ArrayList_Example
{
public static void Main()
{

// Create and initialize a new


The ArrayList Class ArrayList.
ArrayList list = new ArrayList();
When you want to access the elements of an array list.Add("Element 1");
through its index value, you can use an ArrayList list.Add("Element 2");
class. The use of the ArrayList class is an alternative list.Add("Element 3");
to the use of the array and overcomes the limitations of // Display the properties and
using an array. values of the ArrayList.
The limitations of an array are: Console.WriteLine("Count: {0}",
 To resize an array, you have to create a new list.Count);//displays the count of
array, copy the elements into the new array, and elements available in the ArrayList.
then rearrange the array references. Console.WriteLine("Capacity: {0}",
 To remove an element from an array, you need list.Capacity);//finds the number of
to create a copy of the element and then shift all elements that the ArrayList contains.
the remaining elements up. Console.Write("Elements:");
 To add an element in between an array, you PrintValues(list);
have to shift an element down by one place to }
empty a slot. However, you can lose the last
element of the array on rearranging the public static void PrintValues
elements if the number of elements becomes (IEnumerable myList)
greater than the size of the array. {
The following table describes the use of various methods foreach (Object obj in myList)
of the ArrayList class. Console.Write("{0}\t", obj);
Console.WriteLine();
Method Use }
Add() }
Adds an object to the end of
the ArrayList class In the preceding code, list has been declared as
anArrayList data type. The Add() method of the
Remove() Removes the element at the
ArrayList class is used to add elements to the list.
first occurrence of a
specific object from the The Count property of the ArrayList class gives
ArrayList class actual number of elements in the ArrayList variable,
Clear() while the Capacity property gets or sets the number
Removes all the elements
from the ArrayList of elements. The capacity of an ArrayList is the
class number of elements the list can hold. The capacity of an
ArrayList automatically increases as required, when
Insert() Inserts an element into the
elements are added to it.
array list at the specified
index The following figure shows the output of the preceding
code.
TrimToSize() Sets the capacity to the
actual number of elements
in the array list
Sort() Sorts the elements in the
because they reduce the need for boxing, unboxing, and
type casting the variables or objects.
Consider the following example:
public class classData<T>
{
private T data;
public T value
{
Output of the Program get
{
return this.data;
}
set
{
this.data = value;
}
}
}
class Test
{
static void Main(string[] args)
{
classData <string>name = new
classData <string>();
name.value = ".NET ";
classData <float>version = new
classData <float>();
version.value = 4.0F;
Implementing Generics Console.WriteLine(name.value); //
will display .NET
A primary limitation of collections is the absence of Console.WriteLine
effective type checking. This means that you can put any (version.value); //will display 4
object in a collection because all classes in the C# }
programming language extend from the Object base }
class. This compromises type safety and contradicts the The preceding example defines a generic class,
basic definition of C# as a type-safe language. classData, which uses a generic type parameter, T. In
In addition, using collections involves a significant the Main() method, two instances of classData
performance overhead in the form of implicit and have been created by replacing T with string and
explicit type casting that is required to add or retrieve float data types. These objects are used to store
objects from a collection. string and float values respectively. The
To address the type safety issue, the .NET Framework classData class ensures type safety by accepting the
provides generics to create classes, structures, interfaces, required type in its constructor.
and methods that have placeholders for the types they
use. Generics are commonly used to create type-safe
collections for both reference and value types.
The .NET Framework provides an extensive set of
interfaces and classes in the
System.Collections.Generic namespace for
implementing generic collections.

Defining Generics
Generics have introduced the concept of type
parameters, which makes it possible to create classes and
methods that defer the specification of data type until the
class or method is declared and instantiated by client
code.
Generic types perform better than normal system types
Advantages of Generics
Generics have several advantages, such as:
 Reusability
 Type safety
 Performance
Reusability
You can use a single generic type definition for multiple
purposes in the same code without any alterations. For
example, you can create a generic method to add two
numbers. This method can be used to add two integers as
well as two floats without any modification in the code.
Type Safety
Generic data types provide better type safety, especially
in the case of collections. When using generics you need
to define the type of objects to be passed to a collection.
This helps the compiler to ensure that only those object Summary
types that are defined in the definition can be passed to In this chapter, you learned that:
the collection.  Memory allocated to variables is of two types,
Performance value type and reference type.
Generic types provide better performance as compared  Variables of value types directly contain their
to normal system types because they reduce the need for data in a variable.
boxing, unboxing, and type casting of variables or  Reference type variables contain only a
objects. reference to a memory location containing data.
 Structures can be used to hold related data of
various data types in single variable.
 Enumerator allows you to assign symbolic
names to integral constants.
 An array is a collection of values of the same
data type.
 The foreach statement interprets the common
loop process and removes the need for you to
check the array size.
 TheParam arrays are used in the methods with
parameter list when the total number of
parameters is not known.
 The multidimensional arrays stores data in more
than one row (dimension).
 Indexers use an object as an array.
 Indexers have a set of setter and getter methods,
also called accessors.
 The .NET Framework provides the
Collection classes in the System
Let’s Practice namespace.
 Elements in a collection are of the object type.
 AnArrayList class is an alternative of using
an array and allows easy manipulation of values
in an array.
 Generics have introduced the concept of type
parameters.
 Generics have the following advantages:
 Reusability
 Type safety
 Performance
Exercises
Exercise 1
David is a cricket coach of a local team. He is analyzing
the performance of one of his batsman. For this, he
wants a program that should accept the number of recent Reference Reading
matches for which the scores of the batsman need to be
analyzed. After this, the program should accept the Describing Memory Allocation
scores of the batsman for these matches, and then
display the scores in ascending order. Help David create Reference Reading: Books Reference Reading: URLs
the program. Herbert Schildt, C# 3.0: http://msdn.microsoft.com/
Hint: Declare an integer array with a maximum capacity The Complete Reference en-us/library/aa664786
of 100 elements. (VS.71).aspx

Using Structures

Reference Reading: Books Reference Reading: URLs


Exercise 2
Sam is working on an application wherein he needs to Herbert Schildt, C# 3.0: dotnetperls.com/struct-
accept the size of a one dimensional array and its values. The Complete Reference examples
He needs to identify the largest and smallest number in
the array and based on that he needs to display the result. Using Enumerations
Help him to create the application.
Reference Reading: Books Reference Reading: URLs
Simon Robinson, http://msdn.microsoft.com/
Professional C# en-us/library/sbbt4032
(VS.80).aspx
Exercise 3
John needs to create a program that defines a character
array with five elements. He also needs to accept a Implementing Arrays
character from the user, and count the number of times
that character appears in the character array. Help him Reference Reading: Books Reference Reading: URLs
create the desired program. Herbert Schildt, C# 3.0: http://msdn.microsoft.com/
The Complete Reference en-us/library/aa288453
(VS.71).aspx

Implementing Indexers
Exercise 4
David needs to create a program to maintain the details
of the stock of a shop. He needs to ensure that item Reference Reading: Books Reference Reading: URLs
category is Women, Men, Girls, Boys, and Babies. He Herbert Schildt, C# 3.0: http://www.developer.com/
needs to accept item category from the user. In addition, The Complete Reference net/csharp/
he needs to accept item name, number of units, and unit article.php/1547581/Using-
price. Finally, he needs to display all the details. Indexers-in-C.htm
Hint: Use enumerations for item category.
Implementing Generics

Reference Reading: Books Reference Reading: URLs


Herbert Schildt, C# 3.0: http://www.c-
Exercise 5 The Complete Reference sharpcorner.com/
Write a program that accepts the number of players UploadFile/sdhar8po/
playing a game. The program should ensure that the GenericsInCSharp1115200
number of players entered by the user should be in the 5055344AM/
range of 1 to 4 in integer format. Finally, the program GenericsInCSharp.aspx
should store and display the names of the players.
Hint: To validate the integer format, use the int.TryParse
method.
{
Employee e;
public void leave()
Chapter 5 {
e.Calc_Leave()
Extending Existing Classes }
}
You do not always need to create a class from scratch. At class Designer
times, you can create a new class by extending the {
features of an existing class. The process of creating a Employee e;
new class by extending some features of an existing public void leave()
class is known as inheritance. {
This chapter explains how to implement inheritance in e.Calc_Leave()
C#. In addition, it discusses several related concepts }
such as, abstract classes, sealed classes, and interfaces. }
 class Employee
Objectives {
public void Calc_Leave()
In this chapter, you will learn to: {
 Use inheritance .....
 Use abstract classes }
 Use sealed classes }
 Use interfaces class Manager : Employee
{
public void leave()
Implementing Inheritance {
Calc_Leave(); /*The function
C# allows you to implement inheritance by extending
of the base class is available
the features of an existing class to create a new class. Let
here */
us see how to implement inheritance in C#.
}
}
class Designer : Employee
Creating a Derived Class from a Base {
Class public void leave()
{
The following syntax is used in C# for creating derived Calc_Leave(); /*The function
classes in C#: of the base class is available
class <derived_class> : <base_class> here */
{ }
... }
}
Syntactically, there is nothing wrong with the preceding
Determining Inheritance Hierarchies code snippets. However, one of these code snippets
To determine inheritance hierarchies, you must check the depicts the utilization relationship and the other depicts
kind of relationship between the derived classes and the inheritance between the classes.
base class. Ensure that the derived class is a kind of the To choose the more appropriate way of creating the
base class. Manager and Designer classes, you have to analyze
Consider a scenario. You have an Employee, the relationship between the classes. As both the
Manager, and Designer classes. You require the manager and designer are employees, there is a “kind of”
properties of the Employee class to exist in the relationship between the manager and the employee; and
Manager and Designer classes. You can ensure this the designer and the employee. Therefore, it will be
by using any of the following code snippets: more appropriate to inherit the Manager and
 class Employee Designer classes from the Employee class, rather
{ than individually creating an instance of the Employee
public void Calc_Leave() class in the Manager and Designer classes to access
{ the properties of the Employee class. Therefore the
..... second code is more appropriate than the first code in
} this scenario.
}
class Manager
Constructor Invocation in Derived
Classes
When an object of a derived class is created, the
constructor of the derived class as well as the base class
is executed. Constructors are called in the order of base-
to-derived. However, the execution of destructors is
controlled by the garbage collector and the order of their
invocation cannot be determined.
The following code shows the order of invocation of
constructors in derived classes:
using System;
class Base
{
public Base()
{
Console.WriteLine("Constructor of
The following figure shows the output of the preceding
Base");
code.
}
Base()
{
Console.WriteLine("Destructor of
Base");
}
}
class Derived : Base
{
public Derived() Output of the Program
{ Base Class Initialization
Console.WriteLine("Constructor of When creating an instance of a derived class, you can
Derived"); initialize the base class by calling the constructor of the
base class. The base keyword is used to access methods
}
and properties of the base class from a method of the
Derived()
derived class. Using the base keyword, the constructor
{
Console.WriteLine("Destructor of of the base class can be called when the derived class is
Derived"); instantiated.
} The following code shows the use of the base keyword:
} using System;
class BaseDerived class Student
{ {
static int Main(string[] args) private string firstname,identity;
{ public Student(string name, string
Derived obj = new Derived(); id)
return 0; {
} firstname = name;
} identity = id;
}
public string getName()
{
return firstname;
}
public string getId()
{
return identity;
}
Student()
{

}
}
class HostelStudent : Student
{
private int roomno;
public HostelStudent(string name,
string id,int r ): base(name,id)
{
roomno=r;
}
public void getDetails()
{
Console.WriteLine("Name is {0},ID
is {1}, and room number is
{2}",getName(),getId(),roomno);
}

public static void Main(string []


args)
{ Let’s Practice
HostelStudent hs= new HostelStudent
("john","001",5); /* calling Predict the output of the following code:
the constructor of the derived class class Base
*/ {
hs.getDetails(); public Base()
} {
} System.Console.WriteLine
The following figure shows the output of the preceding ("Constructor of Base");
code. }
Base()
{
System.Console.WriteLine
("Destructor of Base");
}
}
class Derived : Base
{
public Derived()
Output of the Program {
In the preceding code, the Student class is the base System.Console.WriteLine
class and the HostelStudent class is derived from ("Constructor of Derived");
the base class. When the derived class is instantiated, the }
constructor of the base class is called to initialize the Derived()
member variables of the base class. The base keyword {
is used to pass the parameters to the constructor of the System.Console.WriteLine
base class. Here, the values of name andid of the ("Destructor of Derived");
student is passed to the Student class. }
}
class BaseDerived
{
static void Main(string[] args)
{
Derived obj = new Derived();
}
}

Using Abstract Classes


An abstract class is defined by using the abstract
keyword before the class keyword.
The following code snippet shows the declaration of an {
abstract class: Carnivorous cn=new Carnivorous();
abstract class ExampleAbstract //This Herbivorous hb=new Herbivorous ();
is an abstract class cn.FoodHabits();
{ hb.FoodHabits();
..... }
} }
However, an abstract class cannot be instantiated as The following figure shows the output of the preceding
shown in the following code: code.
class TestAbstract
{
public static void Main(string[]
args)
{
ExampleAbstract obj= new
ExampleAbstract();
//An abstract class cannot be
instantiated Output of the Program
}
In the preceding code, the abstract method is declared by
}
adding the modifier, abstract to the method. Abstract
method, FoodHabits(), is declared in the abstract
You cannot declare an abstract class as class, Animal, and then the abstract method is inherited
sealed. Sealed classes are classes that can never be in the Carnivorous and Herbivorous classes.
extended or inherited. Abstract methods cannot contain any method body.

Using Abstract Methods


A method can be declared as abstract by specifying the
modifier, abstract before the return type of the
method. The syntax for using an abstract method is:
[access-modifiers] abstract return-
type method-name ([parameters]);
The following code shows the use of abstract classes
with abstract methods:
using System;
abstract class Animal
{
public abstract void FoodHabits();
}
class Carnivorous : Animal
{
public override void FoodHabits()
{ Using Virtual Functions
Console.WriteLine("The Carnivorous
animals eat only meat"); To declare a virtual function, the virtual keyword is
} used before the return type of the function and after the
} access modifier of the function.
class Herbivorous : Animal The following code shows the use of virtual function:
{ using System;
public override void FoodHabits() namespace VirtualFunction
{ {
Console.WriteLine("The Herbivorous class Animal
animals eat only plants"); {
} public virtual void FoodHabits()
} {
class Implement Console.WriteLine("Animals have
{ different food habits");
public static void Main() }
} FoodHabits() method of the appropriate derived
class Carnivorous : Animal class at run time depending on the type of object passed
{ to the callFunction() method.
public override void FoodHabits()
{
Console.WriteLine("The The mechanism of linking a function with an object
Carnivorous animals eat only at run time is called late binding. It is also known as
meat"); dynamic binding. On the other hand, the mechanism of
} linking a function with an object at compile time is called
} early binding. It is also known as static binding.
class Herbivorous : Animal
{
public override void FoodHabits()
{
Console.WriteLine("The
Herbivourous animals eat only
plants");
}
}
class Implement
{
public void callFunction(Animal
Cr)
{
Cr.FoodHabits();
}
}
class ClassMain
{
public static void Main() Let’s Practice
{
Drag and drop the correct keywords in the following
Implement Imp = new Implement();
code such that the output will be “Inside Class C”:
Carnivorous cn = new Carnivorous();
Herbivorous hb = new Herbivorous();
Imp.callFunction(cn);
Imp.callFunction(hb);
Console.ReadLine();
}
}
}
The following figure shows the output of the preceding
code.

Output of the Program


In the preceding code, the base class named Animal Using Sealed Classes
has a virtual function named FoodHabits. The
There may be times when you do not need a class to be
derived classes, Carnivorous and Herbivorous,
extended. You may even want to force users not to
override the FoodHabits() method of the Animal
inherit a class. You could restrict users from inheriting
base class and implement their own functionality. The
the class by sealing the class using the sealed
method named callFunction() takes an argument
keyword. The keyword tells the compiler that the class is
of the Animal class, which in turn will call the
sealed, and therefore, cannot be extended. No class can
be derived from a sealed class. The following is an
example of a sealed class:
sealed class FinalClass
{
private int x;
public void Method1()
{
}
}
A method can also be sealed, and in that case, the
method cannot be overridden. However, a method can be
sealed in the classes in which they have been inherited.
If you want to declare a method as sealed, then it has to
be declared as virtual in its base class. Consider the
following example of a sealed method in a derived class:
using System;
class Math
{
public virtual void Pi() { Let’s Practice
Console.WriteLine("Math.Pi");
Predict the output of the following code:
}
using System;
public virtual void Log() {
using System.Collections.Generic;
Console.WriteLine("Math.Log");
using System.Linq;
}
using System.Text;
}
namespace SealedExample
class Trignometry : Math
{
{
sealed override public void Pi() {
class Derived : SealedClass
Console.WriteLine
{
("Trignometry.Pi");
static void Main(string[] args)
}
{
override public void log() {
SealedClass sealedCls = new
Console.WriteLine
SealedClass();
("Trignometry.Log");
int total = sealedCls.Add(4, 5);
}
Console.WriteLine("Total = " +
}
total.ToString());
In the preceding code, the base class named Math has a }
virtual function named Pi() and Log(). The derived }
class, Trignometry, overrides and seals the Pi() sealed class SealedClass
method of the Math base class. Therefore, the Pi() {
method of the Trigonometry class cannot be public int Add(int x, int y)
overridden by any other derived classes of the {
Trigonometry class. return x + y;
}
}
}
a. Total = 9
b. Total = 5
c. Preceding code will result in compile time error since
the method Add() is not declared as Sealed.
d. Preceding code will result in compile time error since
we cannot derive a sealed class.

Using Interfaces
An interface is similar to a class. However, it simply
defines the structure of the class and does not have any
implementation. An interface can be used in a situation
where you want a set of classes to follow a definite iImp.MethodToImplement();
structure. In this case, you can define an interface with }
the desired structure, and create classes that implement public void MethodToImplement()
the interface. When a class implements an interface, it is {
forced to follow the same structure as the interface. Console.WriteLine
Interfaces define properties, methods, and events, which ("MethodToImplement called.");
are known as the members of the interface. Interfaces }
contain only the declaration of members. Classes and }
structures implement these interface members. Interfaces can inherit members from an existing
Interfaces are different from abstract classes. This is interface. The class, which implements from an
because abstract classes are used when you want only interface, needs to implement all the members of the
few methods to be declared by the base class and the interface.
derived class will implement the functionality.
In C#, a class cannot inherit from more than one class.
However, a class can implement more than one interface.
Therefore, interfaces can be used to implement multiple
inheritance.
Interfaces define what a class can do, but do not define
how the class does it. The following points describe the
need of using interfaces:
 Interface separates the definition of objects
from their implementation.
 Interface allows a class to inherit multiple
behaviors from multiple interfaces.

Working with Interfaces


You can declare only methods, functions, and properties
in interfaces. You cannot declare a variable in interfaces.
Declaring Interfaces
You can declare an interface using the interface Inheriting Interfaces
keyword. The declaration of interfaces is very similar to The following code shows inheritance of an interface
class declaration. Interface statements are public by from an existing interface:
default. The following code snippet shows the using System;
declaration of an interface: interface IParentInterface
public interface IMyInterface {
{ void ParentInterfaceMethod();
//Declare an interface member }
void MethodToImplement(); interface IMyInterface :
} IParentInterface
{
Implementing Interfaces void MethodToImplement();
Interfaces declare methods, which are implemented by }
classes. A class can inherit from a single class but can class InterfaceImplementer :
implement multiple interfaces. The following code IMyInterface
shows the implementation of an interface: {
using System; static void Main()
public interface IMyInterface {
{ InterfaceImplementer iImp = new
//Declare an interface member InterfaceImplementer();
void MethodToImplement(); iImp.MethodToImplement();
} iImp.ParentInterfaceMethod();
class MyClass : IMyInterface }
{ public void MethodToImplement()
static void Main() {
{ Console.WriteLine
MyClass iImp = new MyClass (); ("MethodToImplement called.");
}
public void ParentInterfaceMethod() {
{ public abstract class Furniture
Console.WriteLine {
("ParentInterfaceMethod called."); rotected string color;
} protected int width;
} protected int height;
A class or a structure that implements interfaces also public abstract void Accept();
implements the base interfaces of its inherited interfaces. public abstract void Display();
In the preceding code, the IMyInterface interface }
inherits the member function, class Bookshelf : Furniture
ParentInterfaceMethod(), from the base {
interface, IParentInterface. If a class implements private int numOf_shelves;
the IMyInterface interface, then it implicitly public override void Accept()
implements the IParentInterface interface. {
string str2, str3, str4;
Console.WriteLine("ENTER VALUES
FOR BOOKSHELF");
Console.WriteLine("Enter Color
");
color = Console.ReadLine();
Console.WriteLine("Enter Width
");
str2 = Console.ReadLine();
width = Convert.ToInt32(str2);
Console.WriteLine("Enter Height
");
str3 = Console.ReadLine();
height = Convert.ToInt32(str3);
Console.WriteLine("Enter No. of
shelves ");
str4 = Console.ReadLine();
numOf_shelves = Convert.ToInt32
(str4);
}
Let’s Practice public override void Display()
Write a program that has an interface called {
Characterstics that contains a method called Console.WriteLine("DISPLAYING
display(). Implement the display() method in a VALUES FOR BOOKSHELF");
class named Bird that accepts and displays the type and Console.WriteLine("Color is {0}",
color of the bird. color);
Console.WriteLine("Width is {0}",
width);
Console.WriteLine("Height is {0}",
Activity: Order-processing System height);
Using Abstract Classes Console.WriteLine("Number of
shelves is {0}",
Problem Statement numOf_shelves);
Furniture and Fittings Company (FFC) manufactures }
domestic furniture. Customers provide their }
specifications to the company for the furniture they class Chair : Furniture
want. To handle the increased customer’s orders, FFC {
decides to computerize the order-processing system. The private int numOf_legs;
system should accept the choice of the customer related public override void Accept()
to the attributes of the specified furniture items, such as {
bookshelves and chairs. You need to develop the system string str2, str3, str4;
to accept and display the choices of the customer. Console.WriteLine("ENTER VALUES FOR
Solution CHAIR");
using System; Console.WriteLine("Enter Color ");
namespace FFC color = Console.ReadLine();
Console.WriteLine("Enter Width ");
str2 = Console.ReadLine();
width = Convert.ToInt32(str2);
Console.WriteLine("Enter Height ");
str3 = Console.ReadLine();
height = Convert.ToInt32(str3);
Console.WriteLine("Enter No. of
legs in a chair ");
str4 = Console.ReadLine();
numOf_legs = Convert.ToInt32(str4);
}
public override void Display()
{
Console.WriteLine("DISPLAYING
VALUES FOR CHAIR");
Console.WriteLine("Color is {0}",
color);
Console.WriteLine("Width is {0}",
width);
Console.WriteLine("Height is {0}",
height);
The Output
Console.WriteLine("Number of legs
is {0}", numOf_legs);
}
}
Summary
class BookShelfChair In this chapter, you learned that:
{  OOP enables classes to inherit commonly used
static int Main(string[] args) state and behavior from other classes.
{  Generalization means that multiple classes can
Bookshelf b1 = new Bookshelf(); inherit from the same superclass.
Chair c1 = new Chair();  A class that inherits or derives attributes from
b1.Accept(); another class is called the derived class and the
b1.Display(); class from which it is derived is called the base
c1.Accept(); class.
c1.Display();  Inheritance avoids redundancy in code and
Console.ReadLine(); enables easy maintenance of code.
return 0;  Constructors are called in the order of base-to-
} derived.
}  An abstract class is an incomplete class that
} cannot be used directly.
The output is displayed, as shown in the following  To use an abstract class, other classes can derive
figure. from it.
 A sealed class tells the compiler that the class
cannot be extended further. You cannot derive a
class from a sealed class.
 An interface defines properties, methods, and
events. The properties, methods, and events that
are defined in the interface are known as the
members of the interface.

Exercises
Exercise 1
John is a software developer, who works for Mega
Technologies. He is currently under the project of
geometric calculations. The program that John has to
develop should:
1. Calculate the area of circle.
2. Calculate the volume of the cube.
Help John to develop the program using an interface.

Exercise 2
Smith is currently studying Bachelors in Information
Technology (IT). He has an assignment to develop a
program using the abstract classes, which displays the
following statements:
 I’m a Line.
 I’m a Circle.
 I’m a Square.
He has to create a Draw() method in a program to
display the preceding statements. Help Smith to
accomplish the task.

Reference Reading
Implementing Inheritance

Reference Reading: Books Reference Reading: URLs


Simon Robinson, http://www.exforsys.com/
Professional C# tutorials/csharp/
inheritance-in-csharp.html

Using Abstract Classes

Reference Reading: Books Reference Reading: URLs


Simon Robinson, http://www.exforsys.com/
Professional C# tutorials/csharp/
inheritance-in-csharp.html

Using Sealed Classes

Reference Reading: Books Reference Reading: URLs


Simon Robinson, http://www.exforsys.com/
Professional C# tutorials/csharp/
inheritance-in-csharp.html

Using Interfaces

Reference Reading: Books Reference Reading: URLs


Herbert Schildt, C# 3.0: http://msdn.microsoft.com/
The Complete Reference en-us/library/
ms173156.aspx
Interface
Is a syntactical contract that all the derived classes
should follow.
Glossary ISO
Is an acronym for International Standard Organization.
A
Abstraction M
Is extracting only the relevant information. Method
Access Specifier Is a set of one or more program statements, which can be
executed by referring to the method name.
Is defining the of scope of a class member.
ANSI N
Namespace
Is an acronym for American National Standards Institute.
Is a collection of classes.
Array
Is a collection of values of the same data type. O
Object
Attribute
Is a combination of messages and data.
Is a declarative tag that is used to convey information to
runtime about the behavior of programmatic elements P
such as classes, enumerators, and assemblies. Property
C Provide a public interface for getting and setting values
Class for private attributes of a class, while hiding the
implementation.
Is a declaration, a template, or a blueprint that can be
used to classify objects. S
Compiler Structure
Is a program that processes instructions written in a Is a value type data type.
programming language and translates them into machine U
language. Unboxing
Constructor Means converting from reference type to value type.
Is a special type of method that is invoked when you
create a new instance of a class. V
D Variable
Destructor Is a location in the memory that has a name and contains
Is a special method that is used to release the instance of a value.
a class from memory.
E
Enumeration
Is a value type data type, which assigns symbolic names
to integral constants.
Event
Is an action or occurrence, such as clicks, key presses,
mouse movements, or system generated notifications.
Exception
Is an abnormal condition encountered by an application
during execution.
F
Function
Is a set of statements that performs a specific task in
response to a message.
G
Garbage Collection
Is a process that automatically frees the memory of
objects that are no more in use.
I
Indexer
Helps to use an object as an array.
Inheritance
Is a process of creating a new class by adding some
features to an existing class.

Vous aimerez peut-être aussi