Académique Documents
Professionnel Documents
Culture Documents
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.
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.
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");
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
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#.
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());
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.
Reference Reading
Introducing C#
Using Variables
Objectives
In this chapter, you will learn to:
Use various operators
Use conditional constructs
Use looping constructs
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.
Exercise 7
Write a program to display the highest of any 10
numbers entered. Reference Reading
Using Various Operators
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.
increment();
Console.WriteLine(x);
increment();
Console.WriteLine(x);
Console.ReadLine();
}
}
Number1 = Convert.ToInt32
(Console.ReadLine());
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.
}
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.
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.
}
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 }}}
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.
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
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
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
}
}
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);
}
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.
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
Using Interfaces