1
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 1C# 2010
with Microsoft.Net
Framework 4.0
Pragati Software Pvt. Ltd.
2
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 2Index
Module Particulars Page
Module 1 Getting Started 4
Module 2 Basic Language Constructs 15
Module 3 Class and Object 37
Module 4 Class Library 47
Module 5 Inheritance 59
Module 6 Exception Handling 75
Module 7 Other C# Features 85
Module 8 String, StringBuilder and Dateformats 99
Module 9 Collection classes 117
Module 10 Generics and Nullable Types 129
Module 11 Windows Form Control I 137
3
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 3Index
(Contd…)
Module 13 Working with DB 181
Module 14 Data Bound Controls 226
Module 15 DotNet Framework and Assembly 239
Module 16 Delegate 244
Module 17 Thread 253
Module 18 Introduction to Web Services 273
APPENDIX Windows Form Control II 290
APPENDIX Advance Thread 306
APPENDIX Reflection 320
APPENDIX Serialization 324
APPENDIX Iterators 332
APPENDIX SQL BULK copy 351
4
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 4Module 1: Getting Started
• Overview
¾ Introduction to C# ¾ Types of applications
¾ Understanding some terms: solution, project, Visual Studio IDE ¾ Writing, compiling and running a simple program
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 5
Framework Version
CLR 4.0
.Net Framework 2.0
C# 2.0 VB 8.0.Net Framework 3.5
C# 3.0 VB 9 LINQ AJAX Enhancement for WCF, WPF, WF.Net Framework 3.0
WCF WPF WF Card Space.Net Framework 4.0
C# 4.0 VB 10 PLINQ MEF DLR Code ContractsMEF : The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible
applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well.
DLR : The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 6
.Net Framework
.NET Framework is a common platform for designing, developing and deploying the various types of applications such as:
Console Application, Windows Application, Web Based Application, Class Library Application, Web services, WCF, WPF, WF etc..
A developer can develop application by using any of the language which is compatible with .NET Framework. The languages compatible with .NET Framework are such as C#, VB, J#, VC++, F# etc.
The Base class library provides a comprehensive set of facilities for application development.
The .NET Framework provides a run-time environment called the Common Language Runtime. It runs the code and provides the services which makes the development process easier.
Microsoft provides IDE as a Visual Studio to implement the .NET Framework.
.NET Framework comes with redistributable installer that contains the Common Language Runtime and .NET Framework components which are necessary to run .NET Framework applications.
The .NET Framework is available as a stand-alone executable file, Dotnetfx.exe.
NOTE:Prior to .NET Framework for developing different types of applications different technologies were
used.
E.g. : For developing Console applications languages such as C/C++ was used. For developing Windows based applications VB was introduced by the Microsoft.
For developing and designing web based applications, technologies such as HTML, DHTML, JavaScript, classic ASP were used.
It means for developing specific type of application, one has to use different technologies.
7
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 7Types of Applications
• Console applications.
• Windows applications
• ASP.NET Web applications
• Class libraries
• Custom controls (User defined controls).
• Windows service
• Web Service
We can create multiple kinds of applications such as: Console Applications:
Applications that run on command prompt. Windows Applications:
Desktop application using windows forms. ASP. Net Web Applications:
Browser based applications i.e. Web sites. Class Library:
Components basically are reusable piece of code that contains some business logic. Custom Controls:
We can create our own controls from the existing controls either in windows or in web. Windows Services:
We can create services that run in the background. Web Services:
Web Services are web components. We can have a business logic available on the web that can be shared by people across the world.
8
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 8Features of C#
• Object-oriented features
• Structured exception handling
• Powerful Windows based applications
• Building Web based applications
• Simple data access
• Multithreading
• Simplified deployment
• XML Web Services
Features of C#
C# is a very powerful language. It implements Rapid Application Development Tools for developing various kinds of application.
Full Support for Object Oriented Programming.
Structured Exception Handling helps create and maintain the program with robust error handlers. In this technique, we write a code which detects and traps the errors during execution and prevents application from inconsistent state.
.NET provides an IDE to develop all kinds of applications such as Windows, Web, Console, AJAX based, Mobile etc into one environment using the languages that are supported by framework.
9
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 9Creating a New Project
(Contd...)
2. Language 1. Framework Version 3. Application Template 4. Project Name 5. Project Location 6. Solution Name
Start Microsoft Visual Studio 2010. Click on File > New > Projects
1.Select from the drop down appropriate version of .NET Framework. 2.Choose the language C# from Left hand side project type..
3.On the right hand side from the templates available, select Console Application. 4.Specify the project name.
5.Select the location to save the project. 6.Specify the name for solution.
10
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 10Solutions and Projects
• A solution usually acts as a
container for one or more
projects
• A project typically contains
all the files required for the
application.
1. Solution name 2. Project name 1. Solutions:A Visual Studio solution can include just one project or several projects built jointly by a development team. A complex application might require multiple solutions.
2. Projects:
Visual Studio projects are used as containers within a solution to logically manage, build, and debug the items that comprise your application. The output of a project is usually an executable program (.exe) or a dynamic-link library (.dll) which known as Assembly.
11
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 11Writing the First Program
• Click on Debug -> Start to view the output.
namespace Module01 {
class Program {
static void Main(string[] args) { Console.WriteLine("Hello World..."); Console.ReadLine(); } } }
(Source code: C:\Training\Module01\Module01\Module01\Program.cs)
Namespace is a logical collection of the types such as: class
interface struct enum delegate
In class Program we have Main() method which is known as entry point.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 12
Compilation Process in .NET
Visual Basic
C#
J#
Compiler
CPU CPU JIT JIT Windows CLR MAC CLR Managed codeCompiler
Compiler
.
Net framework supports various languages to develop the applications. A developer may write a code by using any of the language (VB, C#, J#, VC++, F#) which is compatible with .Net Framework. What happens when the code is written and compiled in .Net framework?Every language has its own language compiler. Very first the code is compiled by the language compiler and it produces a MSIL (Microsoft Intermediate Language) code. It is also known as “IL” code.
This MSIL code is now sent to the CLR (Common Language Runtime).
Once the MSIL code is sent to the CLR, only the code which is required during runtime is getting compiled into native machine code. This process is known as “JITing” and it is performed by a component known as “JITer” (Just in Time Compiler).
Once the native machine code is produced it goes through under tight security policy which is known as “CASPOL” (Code-Access-Security-Policy). If this code is safe then only it is executed on CPU. This code is also known as “managed code”.
Same process happens for the other OS also.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 13
Location of .exe file.
1. Location of .exe
2. Exe file
.Exe is always stored at location : project folder\bin\debug.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 14
Components of CLR
Class Loader : It loads all the Base Class Libraries required during execution of code.
Type Verifier : Type verifier checks for the type compatibility. It is also known as “CTS”(Common Type
System). The specification for the types are specified by “CLS” (Common Language Specification).
Exception Manager : Exception manager manages the exception during runtime.
JIT : Just-In-Time compiler produces native machine code which is required while runtime.
Garbage Collector : It is also known as “Heap Manager” or “Auto memory manager”. It releases the
memory by removing unused/out of scope objects. In invokes automatically. One can not predict about it’s invocation.
Security Manager : Once the native machine code is produced, it is sent to the CPU for execution. This
native machine code goes under tight security policy. This security policy is known as “CASPOL” . It is categorized into : 1) Code based Interface 2) Role based Interface.
Thread Manager : Thread manager manages the multi-threading envt.
COM Marshaller : While migrating from old COM application to .NET application ,the type compatibilty of
COM applications with .NET types is marshalled by this component.
15
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 15Module 2. Basic Language Constructs
• Overview
¾ Variables and data types
¾ Operators (arithmetic, relational, logical, assignment, conditional, etc.) ¾ Conditional statements
• if – else
• switch
¾ Looping Constructs• while
• do….loop while()
• for
¾ ArraysPragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 16
Data Types
(Contd…)
The .NET platform provides Common Type System to all the supported languages. This means that all the languages must support the same data types as enforced by common language runtime.
Data Types Description Example
object The ultimate base type of all other types object o = null;
string String type; a string is a sequence of Unicode characters string s = "hello";
sbyte 8-bit signed integral type sbyte val = 12;
short 16-bit signed integral type short val =12;
int 32-bit signed integral type int val=12;
long 64-bit signed integral type long val1=12;
long val2=34L;
byte 8-bit unsigned integral type byte val1=12;
ushort 16-bit unsigned integral ushort val1=12;
uint 32-bit unsigned integral type uint val1=12; unit val2=34U;
ulong 64-bit unsigned integral type ulong val1=12;
float Single=precision floating point float val = 1.23f;
double Double-precision floating point type double val1=1.23;
double val2=4.56D;
bool Boolean type; a bool value is either true or false bool val1=true;
char Character type; a char value is a Unicode character char val1=‘h’;
decimal Precise decimal type with 28 significant digits decimal val = 1.23M;
Formatting Numeric Data C or c – Currency format D or d – double
M or m – decimal F or f – float
17
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 17Variable and Data type Program
static void Main(string[ ] args) {double centigrade; double fahrenheit; centigrade = 33.3;
fahrenheit = (centigrade * 9 / 5) + 32;
Console.WriteLine("33.3 Centigrade = " + fahrenheit + " Fahrenheit."); Console.ReadLine();
}
(Source code: Module02\Module02\01variable.cs)
Variable Declaration
int num;
double salary, balance; string name;
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 18
Common Type System (CTS)
Vi sual Ba sic.NET CLS C# VC++ Common Type System
The Common Type System , is a part of the .net framework describes how the various data types must be
declared, managed and used at runtime and plays a very crucial role for supporting cross language integration. Some of the most common functions it conducts are :
1.Type Safety, Cross language integration and high performance execution of code.
2.It has a set of rules that all .net compliant languages must follow so that the objects created in those languages can interact with each other . It supports the complete implementation of the programming languages.
Common Language Specification (CLS) :
When you write code in one language and this code is then used by other programs
that were developed in different languages, then that code should be CLS
compliant, which simply means that it should abide by the rules specified in the
CLS. The CLS describes features such as common data types for different
languages. CLS compliance is important when software components that are
created in one language will be used by other languages. The CLS is called as a
subset of the CTS because it defines those set of rules that are a part of the CTS
itself.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 19
CLS
C#
int i;
string str;
double dbl;
VB.NET
Dim i as Integer
Dim str as String
Dim dbl as double
.NET Type
System.Int32 i;
System.String str;
System.Double dbl;
If one application written in C# and one application written in VB.NET wants to communicate with each other, how the communication will happen?
In .NET if C# uses int to store numeric value which has a storage size 32 bits and VB.NET uses Integer to store numeric value which also has a storage size 32 bits. Then Common language specification specifies the common type compatible with both the types and produces a result as Int32.
20
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 20Named Constant
static void Main(string[ ] args) {const float Pi = 3.14f;
float radius, area; radius = 10.0f;
area = Pi * radius * radius;
Console.WriteLine("Area of circle = " + area.ToString()); Console.ReadLine();
}
(Source code: Module02\Module02\02constant.cs)
Named constants are created by declaring a variable with keyword const.
Using a named constant can improve the readability of your code, as it becomes a form of documentation. Besides, since a named constant is defined in only one place in a program, if the value of the constant needs to be changed, it needs to be changed only in one place. Thus, use of named constants improves program maintenance also.
21
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 21Writing comments
static void Main(string[ ] args){
/* variable declaration */
const float Pi = 3.14f; float Radius, Area; Radius = 10.0f;
/* Calculation */
Area = Pi * Radius * Radius;
//Printing Result
Console.WriteLine("Area of circle = " + Area.ToString()); Console.ReadLine();
}
Comment
comments can improve the readability (and thereby, maintainability) of source code.
Single Line comment //
text following // up to the end of the line is treated as a single line comment, and is ignored by the compiler. /*
*/
Similarly, any text between /* and the next */ is known as multi line comment, and is also ignored by the compiler.
In C# you can add the contents by using short-cut keys (ctrl+E, C). And for uncommenting short-cut key used is (ctrl_E, U).
22
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 22Taking Input from the User
static void Main(string[ ] args){
const float Pi = 3.14f; float Radius, Area;
Console.Write("Enter the value for radius : ");
Radius = float.Parse (Console.ReadLine());
Area = Pi * Radius * Radius;
Console.WriteLine("Area = " + Area.ToString()); Console.ReadLine(); } Input window Output window
(Source code: (Source code: Module02\Module02\03userinput.cs)
To take input from the user at the runtime we use Console.ReadLine() method and assigning the value to the variable “Radius”.
When we take the input from the command line it is always taken as string type. The data type of the Radius variable is float, so we require to convert string type to float type. For that we are using the method Parse of the float type to convert string value to the float value.
When we print the value we are giving message and then we display the value. So every part of the Console.WriteLine() method has to be of a string type. So for printing we are converting the decimal value of area into string by using ToString() method.
23
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 23Operators
Operator
Language Element
Arithmetic
+, –, *, /, %
Unary
++ ,
--Assignment
=, +=, -=, *=, /=
Comparison
==, !=, <, >, <=, >=
Concatenation
+
Logical operations
&&, ||
e.g.
int num1=5, num2=10, num3;
Arithmetic Operators : num1 + num2; num1 – num2; num1 * num2 ; num1 / num2; num1 % num2; Unary : pre-Increment/pre-decrement : ++num1 / --num1;
post-Increment/post-decrement : num2++/num2 --Assignment : num3=num1 + num2; num1+=num2;
Comparison : num3= num1==num2; It will return 1 (true) if both the numbers are equal or 0 (false) if numbers not equal.
Concatenation : string str1 = “Hello “, str2 = “World”; Console.WriteLine(str1 + str2); Logical operations :
&& (Logical and) :num3=(num1 >5 && num2<=10); It will match both the expression. If both the expressions are true it will return 1 otherwise 0 for false.
24
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 24The if...else Structure
if (expression) statement; if (expression) statement1; else statement2; if (expression) statement1; else if (expression) statement2; else statement3; if (expression) { statement1; if (expression) statement2; } else statement3;If-else is a decision making statement. Returns true if the condition is true or returns
false in else part.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 25
The if...else Structure Example
static void Main(string[ ] args){
int Num1 = 10, Num2=15;
if (Num1 > Num2)
Console.WriteLine("Num1 is greater the Num2"); else
Console.WriteLine("Num2 is greater then Num1");
Console.ReadLine(); }
26
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 26The multiple if Structure Example
static void Main(string[] args){
int a = 5, b = 6, c = 7, min, max;
if (a >= b) { if (a >= c) { max = a; if (b >= c) { min = c; } else { min = b; } } else { max = c; min = b; } } else if (b >= c) { max = b; if (a >= c) { min = c; } else { min = a; } } else { max = c; if (a >= b) { min = b; } else { min = a; } }
Console.WriteLine("max={0} min={1}", max, min); }
27
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 27The switch statement
switch (expression)
{
case value:
statements;
break;
case value:
statements;
break;
default:
statements;
break;
}
28
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 28The switch statement Example
static void Main(string[] args){ int month = 1; switch (month) { case 11: case 12: case 1: case 2: Console.WriteLine("Winter Season"); break; case 3: case 4: case 5: case 6: Console.WriteLine("Summer season"); break; case 7: case 8: case 9: case 10: Console.WriteLine("Monsoon season"); break; default: Console.WriteLine(“Invalid month); } }
29
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 29while loop
static void Main(string[ ] args) { int num = 1; while (num <= 5) { Console.WriteLine("Number = " + num.ToString()); num++; } Console.ReadLine(); }
while (condition) {
statements;
increment / decrement
statement
}
(Source code: Module02\Module02\07while.cs) While loop:
The boolean expression is evaluated, and if true, the following statement (which can be a block) is executed. Thereafter the boolean expression is evaluated again, and once again, if true, the following statement is executed. This process continues until the boolean expression evaluates to false.
A while loop does not execute at all if the boolean - expression is false the first time itself. If you want a loop to be executed at least once before checking the boolean - expression, you should use the do...while loop.
30
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 30do…while Example
static void Main(string[ ] args) { int num = 0; do{ Console.WriteLine("Number = " + num.ToString()); num+=2; } while(num<=10); Console.ReadLine(); }
do
{
statements;
increment / decrement statement
} while (condition);
(Source code: Module02\Module02\08doloop.cs)
Here the boolean expression is evaluated after executing the statement. While the expression is true, the statement is executed repeatedly.
31
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 31for (initialize; condition; increment/decrement)
{
statements;
}
For Loop
static void Main(string[ ] args) {
for (int number = 101; number <= 105; number++)
{
Console.WriteLine("Number = " + number); }
Console.ReadLine(); }
(Source code: Module02\Module02\09for.cs)
32
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 32Array
• Array is a group of elements having same name, same data
type and different index.
stack heap
An array is an ordered collection of elements. Elements of an array can be of primitive types or references to objects.
The value defined in the square bracket is the size of the array. Lower limit start with zero (0)
Upper limit is whatever is the size -1.
The first element of the array has index zero, and the index of the last element is one less than the length of the array. Thus, the first element of the above array is referred to as numbers [0], while the last element is numbers [4]. The length of an array is available with the length field.
Stack memory : All value types are primarily stored on stack area. Heap memory : All reference types are stored on heap area.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 33
Array (continued…)
• int [ ] numbers = new int[5];
Or
int [ ] numbers = new int [ ] {10,20,30,40,50};
Or
int [ ] numbers ={1,2,3,4,5};
1-D Array
Reference
Array Object
10 20 30 40 50
34
34
34
As every string itself is an object, array of strings is nothing but array of references to string objects.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 34
Memory Map of array
(contd…)
String [ ] zones = { "East", "West", "North", "South“ } ;
1-D Array
North
Reference
Array Object
35
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 35Array class and methods
Method Explaination Syntax Example
Reverse() Revereses the order of array elements.
Array.Reverse(array); int [] numbers =new int {24,12,3,43,43}; Array.Reverse(numbers); Sort() Sorts array in
ascending order.
Array.Sort(array); Array.Sort(numbers);
Clear() Sets the range of elements in the array to zero, or to false, or to Nothing depending on the type of array Clear(Arrayname,int,int) Array.Clear(numbers,0,5);
Array class is the base class for all the arrays in CLR.
36
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 36Multidimensional Array
int[,] number = new int[3,3]; number [0,0]= 10;
number[0,1] = 20; Or
int[,] num = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
2-D
Array
Reference
Array
Object
1 2 3
4 5 6
Syntax
Datatype [,] arrayname = new Datatype [rows, columns];
(Source code: Module02\Module02\11MultidimensionArray.cs)
Multi dimensional arrays are always the collection of One dimensional arrays. One 1-D array for each row and one 1-D array of references to preserve references to the 1-D arrays which are carrying values.
37
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 37Module 3: Classes and Objects
• Overview
¾ Classes and Objects ¾ Fields and Methods ¾ Access Control ¾ The “this” reference ¾ Constructors ¾ Overloading ¾ Properties
38
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 38Classes and Objects
• Object
An object is an instance of the class. It is a real time entity.
A class does not have its own existence (memory allocation),
objects created for those classes do. For this reason, objects
are said to be an instance of a class. For e.g. Apple is an
object of fruit class or car is an object of vehicle class.
Each object has an attribute and behaviour. Attribute defines
physical presentation of object and behaviour defines the
tasks which the object can perform.
• Class
A class can be considered as a generalized description of one
or more objects that share the same set of attributes and
responsibilities. A class is known as a user defined data type.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 39
Classes and Objects Continued…
Object Class Attributes Behaviour
car Vehicle Wheels, Engine,
Headlights
Speed(),
john (Emp) Employee Empid, Empname, Salary
CalcBonus()
bankAccoutntObj BankAccount Accno, Accname, Balance
Deposit(), Withdraw()
smith Student Name,
Address, Semester
Get Result()
coffee Product ProductId,
Productname, Quanity, Price
CalcTotalPrice()
An object is anything that is of some interest to an application under development. An object may represent some real-life entity, or an event, or some aspect of the solution strategy to a given business problem. In a banking application, an accountholder (or its data representation within the system) is an object. In a sales information system, a product is an object. In a library management system, students, faculty members, books are all objects.
Objects have attributes; these are characteristics that describe the objects. For example, a student object may have the attributes such as name, address, semester, etc. A book object may have the attributes such as book ID, title, author, publisher, etc.
While talking about objects, we cannot ignore talking about classes. A class can be considered as a generalized description of one or more objects that share the same set of attributes and
responsibilities. For example, all employees belong to an Employee class.
40
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 40Classes and Objects
Rectangle Class
CalcPerimeter() CalcArea()
41
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 41Creating a Rectangle Class
class Rectangle
{
float length=5; float breadth=8;
public float CalcArea() {
return length * breadth; }
public float CalcPerimeter() {
return 2 * (length + breadth); }
}
static void Main(string[] args) { //Class Instantiation
Rectangle rectangleObject = new Rectangle();
Console.WriteLine(“Area={0}”,rectangleObject.CalcArea().ToString());
Console.WriteLine(“Perimeter={0}”,rectangleObject.CalcPerimeter().ToString()); Console.ReadLine();
}
(Source code: Module03\SimpleClassObjectDemo\Rectangle.cs)
A class may have zero, one or more fields; these are variables that hold data for an object of that class. The Rectangle class above has two fields: length, breadth. Every object of this class has its own specific instances of these variables.
A class's methods contain the code that understands and manipulates the state of an object. The Rectangle class has various methods, such as CalcArea(), CalcPerimeter(). These methods modify or return some fields of the class.
The code has one more class called Program, in the main method of which one object of the Rectangle class is created and used. All these aspects are explained in subsequently.
In the above example the Rectangle class is instantiated using the “new" keyword. The
"rectangleObject" is the object reference which holds the Rectangle’s object. Using this reference the CalcArea() and CalcPerimeter() method is invoked through which the data is set.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 42
Properties
• In the previous example the values are assigned in the class
itself.
• What if one wants to get input from the user?
It’s not possible at this point of time. Because in C# by default class members are private. Hence the fields length and breadth are private. Private fields are not accessible from outside of the class.
•
C#.NET provides us solution for this as Properties.
(Source code: Module03\SimpleClassObjectDemo\RectangleVersion3.cs)
You can use both fields and properties to store information in an object. Although public fields and properties are almost indistinguishable from a client-application perspective, they are declared differently within a class. Whereas fields are simply public variables that a class exposes, properties use methods to control how values are set or returned.
Properties have get and set accessor.
Get accessor is used to return the value of a property
Set accessor is used to set the value of a property; they have a parameter, usually called Value, with the same data type as the property itself.
Property can be declare as ReadOnly or WriteOnly which help us to keep check on the variable.
ReadOnly property allows only reading value of the variable. We can not change the value of the variable. Only have “get” accessor.
WriteOnly property allows only setting value for the variable. We can not able to read the value from the variable. Only have “set” accessor.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 43
Properties
(continued…)
//property
private float length;
public float Length { get { return length; } set { length = value; } }
private float breadth;
public float Breadth { …}
Private field
Private field
static void Main(string[] args){
Rectangle rectangleObject1 = new Rectangle();
rectangleObject1.Length = 5; rectangleObject1.Breadth = 8; Console.WriteLine(“Area={0}”,rectangleObject1 .CalcArea().ToString()); Console.WriteLine(“Perimeter={0}”, rectangleObject1.CalcPerimeter().ToString()); Console.ReadLine(); }
In the above code length and breadth are the private fields, hence can not be access from
outside. Therefore public properties are defined for those private fields. It has get and set
access specifiers.
get returns the value and set assigns the to a field.
44
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 44Constructors
•Constructor is a special method which has same name as class.
•Constructor is invoked when the class is instantiated.
•Constructor method does not have any return type.
class Rectangle { float length; float breadth; //constructor public Rectangle() { length = 0; breadth = 0; } }
static void Main(string[] args){
Rectangle rectangleObject1 = new Rectangle();
…;
} Instance creation
Constructor invoked
Constructors
is a special method that is executed when an object of the class is to be created. A constructor is typically used to initialize the state of an object.
A constructor is a special method that must be present in a class for the class to get instantiated. Constructor is having the same name as of the class.
When there is no constructor present, .NET Framework will create one for you. When you instantiate an object by using the new keyword, the class's constructor is called. You can provide initialization code that is guaranteed to run when the object is instantiated. If you write a constructor explicitly in your class, .NET Framework won't create it anymore.
Like other methods, a constructor can take parameters, but cannot return a value.
The constructor of a class can never be explicitly called; it is automatically called when an object of the class is created by you.
45
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 45Constructor Overloading
class RectangleVersion2{ float length; float breadth; //constructor public RectangleVersion2() { this.length = 0; this.breadth = 0; } public RectangleVersion2(float _length, float _breadth){
this.length = _length; this.breadth = _breadth; }
}
static void Main(string[ ] args) {
RectangleVersion2 rectangleObject1 = new RectangleVersion2(); RectangleVersion2 rectangleObject2 = new RectangleVersion2(8, 6); Console.ReadLine(); }
(Source code: Module03\SimpleClassObjectDemo\RectangleVersion2.cs)
A class can have two or more different methods (constructor, methods) with the same name, provided their signature is different.
The signature of a method is • The Name of the method • Number of Parameters • Types of Parameters • Order of Parameter
This feature of having multiple methods with the same name but different signatures is known as
overloading. When you call a method, the compiler determines the actual method to invoke based on
the number and types of parameters supplied by you.
However it is not overloaded by varying only one or more of the following items • The modifiers such as public, shared, static
• The Parameter name
• The Parameter modifiers, such as ref and out • The data type of the return value
46
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 46The “this” Reference
public RectangleVersion2(){
this.length = 0; this.breadth = 0;
}
(Source code: Module03\SimpleClassObjectDemo\RectangleVersion2.cs)
A method of an object can refer to itself by using the “this” reference. One common use of the this reference is when you need to pass a reference to the current object to some other method.
The this reference is also often used when the name of some parameter is the same as the name of a data member.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 47
Module 4: Class Library
• Overview
¾ Overview of Class Library ¾ Create Class Library. ¾ Create a Test Application.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 48
Overview of Class Library
• The .NET framework is a collection of Base Class Libraries.
E.g :- System, System.IO etc.
• As per business requirement you can create your own library
and use it in one or more applications.
• A library is a reusable component which has an extension .dll
which needs to be referenced from the executables.
.dll
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 49
Create Class Library
1. Start Microsoft Visual studio 2010 Æ New Project. 2. From the project types select Class Library. 3. Name it as HRSystem.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 50
Create Class Library
public class Employee {private int empId; private string empName; private double salary; public Employee() {… }
public Employee(int id,string Name, double sal) { this.empId = id; this.empName = Name; this.salary = sal; } //properties ....
public double CalcBonus(double percentage) {
return salary * percentage; }
}
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 51
Creating Class Library continued…
• Build EmployeeLibrary.
• It will generate .DLL file.
Menu options for building project:
1. Click on Build Menu -> Build EmployeeLibrary.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 52
Create a Test Application
1. Add a new Console Application in the same solution. 2. Save it as ABCCorporation.
3. Add reference to ABCCorporation project.
Menu option for adding the project:
1. File -> New Project -> Console Application.
2. Save as ABCCorporation.
3. From the solutions drop-down list select -> Add to Solution.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 53
Adding reference of dll to Application
Menu options:
1.Click on Project -> Add reference .
2.From the dialogue box select projects tab -> select EmployeeLibrary.dll. (It the dll
and application is in the same solution otherwise click on browse tab and select the
required dll from the path).
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 54
Creating a Test Application
using EmployeeLibrary;
class Program {
static void Main(string[] args) {
Employee employee = new Employee(1,"Trupti", 25000); double bonus=employee.CalcBonus(0.3); Console.WriteLine(“Bonus={0}”,bonus); Console.ReadLine(); } }
(Source code :
C:\Training\Module04\EmployeeLibrary\ABCCorporation\Program.cs)
54
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 55
Set startup project
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 56
Static field
• Static field is used when we want to have values that are
shared across all instances of a particular class.
• Static fields and static constants enable this to happen by
belonging to the class and not to the actual objects.
• In your application, you can declare a variable and refer to it
regardless of which instance of an object you are using. Such
a variable is called static.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 57
Static field
public class Employee {……
private static int Id=0; public Employee() {
empId = 0;
empName =“unknown”; salary = 0; }
public Employee(int id,string Name, double sal) {
++id;
this.empId = id; ……
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 58
Assignment
• Create a class library project. Add Product class with
following members:
Product
-productId ; -productName ; -unitPrice ; -Quantity + GetProducts(productname,unitprice,Quantity);• productId must me auto incremented.
• Display totalprice of product available
59
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 59Module 5. Inheritance
• Overview¾ Object Oriented Concepts ¾ Bank Case Study
¾ Inheritance
¾ Constructor in extended classes ¾ Overriding methods
¾ Polymorphism
¾ Use of Sealed keyword ¾ Abstract class and method ¾ Declaring Interface ¾ Implementing Interface
60
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 60Object Oriented Concepts
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
Abstraction refers to the description of externally visible behavior of an object. Abstraction is used to describe what an object does, rather than how it does it.
Encapsulation is a description of the internal data structures and internal implementation that give rise to this externally visible behavior. Encapsulation deals with how the object does it.
Inheritance facilitates reusability of code. A new class can inherit all the properties and methods of another existing class.
Polymorphism refers to the ability to hide many implementations behind the common interface. Using polymorphism, a single name may denote objects of many different classes.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 61
Bank Application
• Create a class library project.
• Save it as BankLibrary.
• It will provide Business Logic of Banking Services.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 62
A BankAccount Class – the Super Class
public class BankAccount {…. ;
public BankAccount() { ….;
}
public BankAccount (string AccName, double Balance) {
…. ; }
public int AccNumber { get ; } public string AccName { get ; set ; } public double Balance { get ; set ; }
public double Withdraw(double amount) { …..; }
public double Deposit(double amount) { ….. ; }
}
(Source code: C:\Training\Module05\BankLibrary\BankLibrary\BankAccount.cs)
63
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 63Inheritance
Inheritance is a powerful feature of OOP. It provides following
features:
•Reusability
•Easy maintenance of code.
•Extendibility
Inheritance
Inheritance is a powerful feature of object-oriented programming languages. This refers to the ability of a class to inherit the fields and operations of another class, and extend these further.
Inheritance can also be useful when two or more classes have some fields and operations in common. Instead of duplicating these common aspects in various classes, we can keep them in a base class, that other classes inherit from.
For example, in a banking application, we may have a SavingsAccount class as well as a
CurrentAccount class. Both these classes may have some common operations and fields, in addition to having their own specific fields and operations. Such common fields and operations can be kept in a common base class called BankAccount. The SavingsAccount and CurrentAccount classes can then inherit from the BankAccount class.
In .NET, there is a class called Object. Every other class explicitly or implicitly inherits from the Object class.
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 64
Access Specifiers
Visibility / Access Specifier
private protected internal public protected internal
Same class Yes Yes Yes Yes Yes
Derived class in
same assembly No Yes Yes Yes Yes
Other class No No Yes Yes Yes
Other class in
other assembly No No No Yes No
Derived class in
65
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 65The SavingsAccount Class – the Sub Class
public class SavingsAccount : BankAccount {
….;
static SavingsAccount() { …. ; }
public SavingsAccount(string AccName,double Balance,bool IsSalaryAccount) :base(AccName,Balance) { ….. ; }
public double CalculateInterest() { …. ; } }
Using Derived class object
static void Main(string[ ] args) {SavingsAccount savingobject = new SavingsAccount();
…. ; }
(Source code: Module04\Inheritance\SavingAccount.cs)
An object of the SavingsAccount class would have all the fields other then private of its base class as well as the ones additionally defined within that class. Similarly, on an object of the SavingsAccount class, all the public and internal operations of the BankAccount class can be applied.
In this program we have created the instance of SavingsAccount class, which is the derived class of the BankAccount class. All the members of the BankAccount class are created inside the memory of the SavingsAccount instance. It is calling the methods inherited from its base as well as of its own.
66
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 66Calling parent class constructor
class BankAccount {public BankAccount(float balance) { …. ;
} }
class SavingsAccount : BankAccount { public SavingsAccount(float balance, bool IsSalaryAccount) : base(balance) { .. } }
Object
BankAccount
SavingsAccount
(Source code: Module04\Inheritance\BankAccount.cs) (Source code: Module04\Inheritance\SavingAccount.cs) (Source code: Module04\Inheritance\Program.cs)
A derived class must choose one of its super class constructors to invoke. The part of the object that is inherited from a super class must be initialized properly by the super class itself.
67
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 67Overriding Methods
•A method in sub class with the same signature as a super class has
but with different implementation is known as method overriding.
•Same signature means methods must have
¾same name.
¾same number of arguments
¾same type of arguments.
¾same access specifier
•Keyword virtual is used in base class method definition.
•Virtual indicates that this method can be overriden by sub class.
A subclass can replace its super class's implementation of a method with one of its own. This is known as overriding a method. Both the signature and return type must be the same as the super class.
In .Net by default method of super class cannot be overridden by sub class. For this sub class require permission from the super class
Super class method should have keyword virtual and sub class method should have keyword
override.
virtual indicates that this method can be overridden by an identically named method in a derived class. virtual is the default setting for a method that itself overrides a base class method.
Override keyword specifies that a property or method overrides a member inherited from a base class. This keyword indicates that method overrides an identically named method in a base class. The number and data types of the arguments, and the data type of the return value, must exactly match those of the base class procedure.
68
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 68Overriding Methods continued…
class BankAccount {public virtual void Withdraw(float amount) { …. ; } }
class SavingsAccount : BankAccount {
public override void Withdraw(float amount) { ….. ; } public override ToString() { …. ; }
}
(Source code: Module04\Inheritance\BankAccount.cs) (Source code: Module04\Inheritance\SavingAccount.cs) (Source code: Module04\Inheritance\Program.cs)
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 69
Polymorphism
• Polymorphism is a Greek word which means “many-shaped”.
• It has two distinct aspects:
¾ At run time object of inherited class may be treated as object of base class .
¾ Base classes may define and implement virtual methods and inherited classes may override these methods , which means inherited classes provide its own definition and implementation.
70
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 70Polymorphism
class BankAccount {….. ;
public int AccountNumber { ….. ; } public float Balance { ….. ; }
public BankAccount() { ….. ; } public BankAccount(float _balance) {
….. ; }
public void Deposit(float amount) { ….. ; }
public virtual void Withdraw(float amount) { … ; }
}
class SavingsAccount : BankAccount
{ ….. ;
static SavingsAccount() { …. ;} public SavingsAccount() { ….. ; } public SavingsAccount(float balance, bool IsSalaryAccount) : base(balance) { ….. ; }
public float CalculateInterest() { ….. ; }
public override void Withdraw(float amount)
{ …. ; } }
class CurrentAccount : BankAccount {
…… ;
public CurrentAccount(float balance, float overdraftlimit) : base(balance) { ….. ; }
public override void Withdraw(float
amount) { ….. ; } }
static void Main(string[ ] args) {
BankAccount Bankref;
Bankref = new SavingsAccount(7000,true); Bankref = new CurrentAccount(4000, 2000);
71
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 71Preventing Overriding
class BankAccount {public virtual void Withdraw(float amount) { …. ; }
}
class SavingsAccount : BankAccount {
public sealed override void Withdraw(float amount) {
….. ; } }
(Source code: Module04\SealedExample\BankAccount.cs) (Source code: Module04\SealedExample\SavingAccount.cs) (Source code: Module04\SealedExample\SubSavingAccount.cs)
You can prevent subclasses from overriding the implementation of a method of a super class, by making it sealed.
You can even make an entire class sealed, thereby preventing any extension of that class. All the methods of a sealed class are implicitly sealed.
It can improve security. If a class is sealed, you know that nobody can extend it, and therefore, nobody can violate its contract. Similarly, if a method is sealed, you can rely on its implementation details.
72
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 72Preventing Inheritance
sealed class SavingsAccount : BankAccount
{ }
class SubSaving : SavingsAccount // compile time error {
}
Sealed classes are primarily used to prevent the inheritance. A sealed class can not
be a base class. But it can be instantiated.
73
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 73Abstract Class
•The abstract keyword enables you to create classes and class
members solely for the purpose of inheritance.
•The purpose of an abstract class is to provide a common definition
of a base class that multiple derived classes can share.
•An abstract class can not be instantiated.
public abstract class BankAccount
{
public abstract void Withdraw(float amount);
}
Abstract class
Abstract method
You can mark a class as abstract, which means that the class cannot be instantiated. This way you can create a class that cannot have objects, but serves as a base for other subclasses.
For example in a bank we can have account as either saving or current but we cannot have account type as a bank.
The use of this class would be only to extend it to SavingsAccount and BankAccount class for reducing duplication of work and maintenance.
The opposite of abstract is concrete; a concrete class can be instantiated. For example, Clerk, Executive and Manager would be concrete classes, extending the Employee class.
For example, SavingsAccount and CurrentAccount would be concrete classes, extending the BankAccount.
74
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 74Interface
•An interface contains only the signature of methods, delegates and
events.
•The implementation of the methods is done in the class which
implements the interface.
•An interface can inherit from one or more base interface.
public interface Iinterest
{
float CaclulateInterest(float irate); }
class SavingAccount : BankAccount, Iinterest { public float CaclulateInterest(float irate) {
…. ; } }
Method signature
Interface
implementation
An interface is a way to declare a type consisting only of abstract methods, Events or Properties. An interface provides a protocol binding to the classes that implement it.
An interface cannot be instantiated. It consists of abstract methods, Events or Properties, i.e., it does not contain any implementation. An interface also cannot contain any variables.
75
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 75Module 6. Exceptions Handling
• Overview
¾ What is Exception Handling? ¾ The “try-catch” Structure ¾ The finally Clause ¾ The throw Cause ¾ User Defined Exception
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 76
What is an Exception Handling?
• Error which occurs during runtime is known as Exception.
• The mechanism to handle such errors during runtime is called
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 77
try-catch-finally
• C# provides 3 keywords to handle an Exception.
¾ try :- The try keyword is required. It lets the compiler know that you are attempting a normal flow of a program.
¾ catch :-During runtime if any exception occurs instead of letting the program crash the flow of the program can be transferred to cache section. catch block is always followed by try.
¾ finally :- This block executes always. It is optional to use finally.
• Syntax for try-catch-finally
try
{ error prone code; }
catch
{ statement for exception handling ; }
finally
{ statement for clean up ; }
Structured Exception Handling concept is introduced in .NET Framework. The
System.Exception is the base class for all the exceptions in .NET. C# provides three
keywords try, catch and finally to do exception handling. The try keyword encloses the
statements that might throw an exception whereas the catch keyword is used to handle an
exception if one exists. The finally clause can be used for doing any clean up process
78
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 78Understanding Exceptions
static void Main(string[ ] args){
int num1, num2, ans; num1 = 10;
num2 = 0;
ans = num1 / num2;
Console.WriteLine("Answer = " + ans); Console.ReadLine();
}
Exception occurs here
There are three types of errors which occurs in program, Syntax errors, run-time errors and
logical errors. Exception handling is mechanism to detect and handle run time errors.
.NET provides us Exception Handling techniques to overcome such situations.
There are two types of exceptions:
System Exception - Exceptions generated by CLR.
Application Exception - Exceptions generated in application
When we run the above code, it will get compile but at run time when control come to the
line “ans = num1 \ num2", it will throw an exception. We require to manage this type of
error which is known as Exception Handling
79
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 79Exception Handling Mechanism
static void Main(string[ ] args) { …. ;
try {
int num1, num2, ans; num1 = 10;
num2 = 0;
ans = num1 / num2;
Console.WriteLine("Answer = " + ans);
}
catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); }
}
(Source code: Module05\ExceptionHandling\ExceptionHandling\Program1.cs)
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. If there is no exception occurred inside the try block, the control directly transfers to finally block. The statements inside the finally block is executed always.
80
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 80Multiple Catch Block
int num1, ans;
int[ ] numarray = new int[1];
try {
num1 = 10;
numarray[0] = 5;
ans = num1 / numarray[1];
Console.WriteLine("Answer = " + ans); }
catch (DivideByZeroException ex) { …. ;
}
catch (IndexOutOfRangeException ex) {
Console.WriteLine(ex.Message); }
catch (Exception ex) { } finally { }
(Source code: Module05\ExceptionHandling\ExceptionHandling\Program2.cs)
A try block can throw multiple exceptions, which can be handled by using multiple catch blocks.
We can use generalized Exception class to handle any type of runtime exception. Add the generalize catch block as the last catch block in the hierarchy otherwise at the compile time it will give an error. “A previous catch clause already catches all exceptions of this or of a super type
('System.Exception')”
Some of the Exception classes are
System.Exception System.DevideByZeroException System.NullReferenceException Syste.InvalidCastException System.IndexOutOfRangeException etc.
81
Pragati Software Pvt. Ltd., 312, Lok Center, Marol-Maroshi Road, Marol, Andheri (East), Mumbai 400 059. www.pragatisoftware.com 81finally
•finally : Code in finally block is always executed. It contain clean
up code to release the resources.
int num1, ans;
int[ ] numarray = new int[1]; try {
…; }
catch (DivideByZeroException ex) { …. ;
}
catch (IndexOutOfRangeException ex) { …;
}
finally {
Console.WriteLine(“End of Main Block”); }
Finally can be used in such cases where it’s needed to free-up the resources always. Finally block is optional.