Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 103

Basic .

NET Programming Using C#


Day 1

Course Objectives
To understand .NET technology and .NET framework To gain ability to work in Visual Studio 2008 Team System IDE To recap Object Oriented Concept and its use in C# To gain ability to work with windows programming and event handling Usage of built-in testing and code analysis tools in Visual Studio 2008 Team System in .NET framework

What is C# and where C# is being used


It is one of the most powerful object oriented programming language from Microsoft It enables programmers to build a wide range of applications for the Microsoft .NET platform The type of application that can be developed are:
Console Application Windows Application ASP.NET Web Application Web Service Mobile Web Application Class Library Windows Control Library Web Control Library Smart Device Application

Course Pre-requisites
Fundamental programming skills C as a programming language Object Oriented Programming Concepts

Introduction to .NET Technologies

Why .NET?
Need to create a new project re using Marketing Module of ABB Project developed in VB.Net Inventory Module of XYZ Project developed using Java Sales Module of EZEE Project developed using C++

Applications developed in different languages. Incorporating them in a single project will be a NIGHTMARE!
6

Why .NET?
A nightmare? Not anymore. Microsoft .NET is a simple solution to this seemingly nightmarish situation. Equipped with various new features, it provides you with interoperability

Interoperability
Components of applications written in one programming language can be used for applications developed in other programming languages

Evolution of Technology Internet


Positives of Internet Browsing Era: Global connectivity Simplicity Mainstream

Browsing Era

GUI Era

Character PC Era Terminal Mainframe Era

Negatives of Internet Browsing Era: Read-only No user control Too many islands Keyboard only
8

The .NET Evolution


Application

Code and data structures

Before COM, applications were completely separate entities with little or no integration

The .NET Evolution

COM provides a way for components to integrate; However, each component must provide the plumbing and objects cannot directly interact
10

The .NET Evolution

With the .NET Framework common language runtime (CLR), components are built on a common substrate; No plumbing is needed and objects can directly interact
11

Need for .NET Framework


Problems with integration of application developed with multiple technologies Limited cross-language interoperability

COM technology drawbacks


COM components registration, unloading Dynamic Link Library (DLL) Hell

Hence Microsoft .NET Framework a computing platform for developing distributed applications for the Internet.
12

.NET
What is .NET? The set of Microsoft software technologies Connecting the world of information, systems, people and devices. Small applications communicating with other applications
Located on the same machine or Via the Internet.

What is .NET Framework? A new computing platform Simplifies application development in the highly distributed environment of Internet

13

NET Design Goals


Simplify Processes Provide a Common Model Provide Security Ensure Acceptability Availability Reliability
14

Features of .NET
Single programming model Integrity with COM
Distributed Systems

Portability with compiled applications

Rich User Interface

Extensibility Multiple Language support

Easy Deployment

15

.NET Languages and Execution Model Source


code
VB C# C++ Compiler Compiler Assembly IL Code Compiler Assembly IL Code

Managed code

Assembly IL Code

Common Language Runtime


JIT Compiler
Native Code

Operating System Services

16

CLR Execution Model


Source Code
Development Machine

Start

N CLR Header Y CLR Services

OS

Compiler

EXE/DLL (IL)

Policy
Class Libraries (IL)

IS Permissions?

Class Loader
Target Machine

Security Exception

Y Is Type Safe ?
Y N Is PreJIT ? JIT N Type Safe Exception

JIT Compiler

Managed Native Code

Call to an uncompiled method

Security Check

Execution

Y Execution

17

Features of CLR
Automatic Memory Management
Provides garbage collection

Language Interoperability

Platform Independence
Security Management
Provides Code Access Security (CAS) Type Safety
18

Common Type System


The CLR defines the common type system (CTS) All .NET languages map into the CTS CLR types are defined under the System namespace. All .NET languages provide their own keywords that map to the underlying CTS types
C# int keyword = System.Int32 VB.NET integer keyword = System.Int32
19

Common Language Specification (CLS)


CLS is a set of basic language guidelines that specify the features needed by .NET applications to fully interact with other objects regardless of their implementation language. Created to improve language interoperability
CLS is a set of guidelines and is a subset of CTS Most of the Framework Class Libraries are CLS compliant Cannot overload based on return type Unsigned integer types are not allowed on public methods Arrays index has to start from 0.
20

Assemblies
Assemblies are fundamental building blocks of a .NET Framework application. They contain the types and resources that make up an application One Assembly can contain one or more files. When you compile your source code, by default the exe/dll generated is actually an assembly An assembly consists of four internal parts: Assembly Manifest or Metadata Type Metadata IL code Resource files

21

Private and Shared Assembly


Assemblies can be either private or public. The assembly which is used only by a single application is called as private assembly A private assembly is integral to the application. A shared assembly can be used by multiple applications Instead of each client application having its own copy of DLL, the DLL can be placed in Global Assembly Cache, which is shared to all client applications.
22

Recap - Object Oriented Programming

What is a Class ?
A Class
Is a blue print used to create objects. Is a software template that defines the methods and variables to be included in a particular kind of Object.

Examples :
Employee, SoftwareEngineer, TechnicalEvangelist, Payroll

A class contains state and behavior State (Member Variables)


Variables defined inside the class Not exposed to external world

Behavior (Member Methods)


Functions defined inside the class Behavior exhibited by the class to external world Exposed to external world

24

What is an Object ?
An object
Is a unique, identifiable, self-contained entity that contains attributes and behaviors.

An object is an instance of a class

25

Introduction to programming using C#

Features of C#
Object-oriented Simpler language
Compared to earlier OO languages like C++, it is simple Designed considering the pitfalls of earlier languages

Robust Architecture Neutral / Portable Secure


Built -in security features like absence of pointers and confinement of the C# program within its runtime environment

Support for Multithreading at language level Designed to handle Distributed applications

27

Structure of a C# Program

Structure of a C# program
using System; class FirstProgram

{
public static void Main() { Console.WriteLine(Hello World); } }

<<Demo : Structure of C# program >>

29

Structure of a Class in C#
class ClassName { DataType1 MemberVariable1; ClassType2 Object2; /* A data member can be defined using 1) primitive types (int, float, string ) 2) user defined structures 3) object reference of a class */

ClassName( parameters ) { /* The constructor is used for members initialization during the object creation */ } return-type MethodName( parameters ) { /* All the application logics have to be placed inside the methods. A method must be placed inside a class.*/ } }// End of the class

30

Namespace

Namespaces
Namespaces provide a way to uniquely identify a type Provides logical organization of types Namespaces can span assemblies Can be nested The fully qualified name of a type includes all namespaces

32

Namespaces
The fully qualified name of a type includes all namespaces Namespaces are mainly used to distinguish between the types having same names Within a namespace, the names of all the types should be unique The Base Class Library (BCL) is a standard library available to all languages using the .NET Framework.

namespace Insys.N1 {//is referred to as N1 class C1 { // is referred to as Insys.N1.C1 class C2 { // is referred to as Insys.N1.C1.C2 } } namespace Insys.N2 { //is referred as Insys.N1.N2 class C2 { //is referred as Insys.N1.N2.C2 } Fully Qualified } name }

33

Data Types in C#
Value Types Value types include simple types like char, int, float, enum types, and struct types Variable holds the actual value Reference Types Reference types include class types, interface types, delegate types, and array types Variable holds the reference of memory location

Allocated on stack
Assignment of one value type to another copies the value

Allocated on heap
Assignment of one reference type to another copies the reference

34

Constructor

Constructor
Constructors are used to initialize the data members during the object initialization A class can have any number of constructors The name of the constructor should be same as the class name The constructor does not have return type, not even void To exit from the constructor, return statement return; can be used.

36

Default Constructor
class Employee { public int empID; public float salary; } /* To create an object of Employee class */ Employee empObj ; empObj= new Employee(); empObj

empID = 0 salary = 0.0

In the above code snippet, Employee() is a constructor It can be confirmed with the fact that its name is same as the class name For the class Employee, no constructor is written A constructor with no parameters will be supplied automatically for a class that is written with no constructor. This constructor is called as Default Constructor. In the above code snippet, Employee() is the default constructor

37

User-defined Constructors
class Employee { public int empID; public float salary; /* user defined constructor with two parameters */ public Employee(int empIDVal, float salaryVal) { empID = empIDVal; salary = salaryVal; Note: } Employee empObj = new Employee(); /* user defined constructor will results in compile time error. with one parameter */ public Employee(int empIDVal) { For a class with user-defined empID = empIDVal; constructors, default parameter-less } constructor will NOT be supplied } // end of class Employee 38

automatically.

<<Demo : User-defined constructors>>

Constructors Best Practices


Use application logic in constructors carefully. Try to minimize unnecessary database operations in constructors. This is a performance overhead. Do not write redundant code in overloaded constructors. This will become a huge maintenance issue as your class hierarchy grows and you start implementing more overloaded constructors in your derived classes. NOTE : overloading will be covered on Day2

39

Access Specifiers
C# provide five access specifiers, they are as follows : public private protected internal protected internal

40

String and StringBuilder

Predefined Types - String


A sequence of characters Strings are immutable (once created the value does not change) String is Reference type and string class in C# is an alias of System.String class in the .NET framework The following special syntax for string literals is allowed as they are built in data types.
string empName = Sreekanth;

C# Type
string

System Type
System.String

42

Predefined Types - StringBuilder


Every time some modifications are done to the string a new String object is created StringBuilder class can be used to modify string without creating a new string object Available in System.Text Namespace Properties:
Length

Methods
Append() Insert() Remove() Replace()

StringBuilder str = new StringBuilder (hi); str.Append(how are you?) str.Insert(6,How do you do?);

43

String & StringBuilder Best Practices constants for the string literals you use instead of Always declare
enclosing them in .
string status = "ACTIVE"; const string C_STATUS = "ACTIVE";

Avoid String concatenation using + operator, instead use StringBuilder for concatenation
string message = hello";

message += welcome"; message += to"; message += Dotnet";

StringBuilder message; message= new StringBuilder(); message.Append(" hello "); message.Append(" welcome "); message.Append(" to "); message.Append(" Dotnet "); 44

Parameter Types

access-specifier return-type MethodName( parameters ) { /* All the application logics have to be placed inside the methods. A method must be placed inside a class.*/ }

Methods

Local Variables for a method


Variables and objects created inside a method Parameters passed to method

By default, all the Value Types are passed by values to the methods By default, all the objects are passed by reference to the methods

46

Parameters Types
The default behavior of passing the parameter can be modified using following parameter arguments (also called as method parameter keywords)
out
It can be used to receive more than one processed output from a method

ref
It can be used to pass variables by reference

params
It can be used to pass zero or more values to a single parameter

47

out to have multiple result values from a method


Characteristics of out parameter:
may not be initialized before the method call should be assigned with a value inside the method out keyword must be specified in both method call and method definition method call can not pass direct values. This will result in compiler error.

48

out parameter type continued


/* Method definition */ void GetEmpDetails(out string name, out float sal) { name=empName; sal = salary; } /* Method Call */ float sal; string name; GetSalary( out name, out sal );

<<Demo : Out parameter>>

49

ref passing value types arguments by reference Characteristics of ref parameter:


should be initialized before the method call ref keyword must be specified in both method call and method definition method call can not pass direct values. This will result in compiler error
/* Method definition */ void Change(ref int num) { num = num + 100; } /* Method Call */ int no = 10; Change( ref no ); /*now the value of no is 110 */ <<Demo : Ref parameter>>

50

params used to pass unlimited arguments parameter Characteristics of params


should be the last parameter in the parameters list. A method can have only one params parameter must be a single dimensional array The params keyword must be specified only in the method definition

/* A method definition with params */ void Print(int data, params int[] list) { /* print logic statements */ } /* The various ways of invoking the print method - Print(10 ); Print(10, 1, 2, 3, 4); Print(10, 1, 2, 3, 4, 5, 6, 7); int [ ] num = {1, 2, 3, 4}; Print( 10, num);

*/

51

Indexer (1 of 2)

Indexer permits members of an instance of a class or struct to be indexed in the same way as elements of array. Indexers are similar to properties except that the name of the indexer is this followed by a parameter list. The signature of indexer is
<modifier> <return type> this [formal argument list]

The modifier can be private, public, protected or internal The indexer has get and set blocks. The formal-argument-list specifies the parameters of the indexer.
52

<<Demo : Indexer Demo>>

Indexer (2 of 2)
A get accessor returns a value. A set accessor assigns a value. The this keyword is used to define the indexers. The value keyword is used to define the value being assigned by the set indexer. Indexers do not have to be indexed by an integer value only; it is up to you how to define the specific look-up mechanism. Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array. C# do not have the concept of static indexers Indexers can be overloaded. A class can have more than one indexer with different signatures
53

Indexers vs. Properties


Indexer An indexer signature. is identified by Properties its A property is identified by its name. An indexer must be an instance property can be static or an instance member member. Accessed through an index. Accessed through a simple name. A get accessor of an indexer has the A get accessor of a property has no same formal parameter list as the parameters. indexer. A set accessor of an indexer has the same formal parameter list as the A set accessor of a property contains indexer, in addition to the value the implicit value parameter. parameter. Allows methods on an object to be Allows methods to be called as called as though the object is an though they were public data array. members.
54

Inheritance
Inheritance follows the is-a relationship between classes The parent class is the base class and the inherited class is the derived class

A derived class cannot access the private members of its base class
Inheritance leads to reusability and extensibility of existing code

55

Inheritance

class TechnicalEvangelist : Employee - class Employee is inherited by the class TechnicalEvangelist. Class Employee can be called as Super or Parent or Base class. Class TechnicalEvangelist can be called as Sub or Child or Derived class. All the public & protected members of parent class can be accessed in the child class as local members. Public member is inherited as a public member by the child class Protected member is inherited as a protected member by the child class No multiple inheritance is available.

56

Protected access specifier (1 of A 2)protected member is accessible only inside its class & its descendants
When a class needs a private member with visibility to its descendant classes, protected access specifier can be used
class Employee { private int age; public string name; protected DateTime birthDate; } class TechnicalEvangelist : Employee {
/* name and birthDate, inherited from Employee class, can be accessed here just like any other local member class */ of this Technical Evangelist

}
57

<<Demo : Inheritance>>

Protected access specifier (2 of 2)


The protected member is not accessible outside of the class and its descendants class EmployeeDemo
{
public static void Main() { Employee empObj = new Employee();
//public member is accessible outside the class

empObj.name = "Jack";
//protected member NOT accessible outside the //class, hence results in compile time error

DateTime empBirthDate = empObj.birthDate; } }


58

Sealed modifier : classes

A sealed class is one that cannot be used as a base class. In other words, a sealed class can not be extended further by any other class. Classes can be declared as sealed by putting the keyword sealed before the keyword class in the class definition

sealed class SoftwareEngineer { /* class members are placed here */ } class DotNetSoftWareEngineer : SoftwareEngineer {
/* this class compilation will be a failure as the sealed class can not be inherited */
59

Inheritance and Constructors (1 of 5)


The parent class constructor will be reused along with child class constructor. Before executing the child class constructor, any one of the parent class constructor must be executed. This is to initialize the inherited data members in the child class during its object creation.

Whenever a child class object gets created, the base class constructor gets invoked (known as constructor chaining).
60

Inheritance and Constructors using 5) (2 ofSystem;

Discussion: Using the given classes when we class Employee { create an object of SoftwareEngin public Employee() class, the output will be { Empoyee Console.WriteLine("Employee"); SoftwareEngineer Reason: } Before executing a constructor of } the derived class, the parent class class SoftwareEngineer: Employee { constructor with no-parameters public SoftwareEngineer() will be automatically executed firs

{ Console.WriteLine("SoftwareEngineer");

}
}
61

<<Demo : Inheritance and constructors>>

Inheritance and Constructors using 5) (3 of System;


class Employee { /* no constructor */ }

Discussion: Using the given classes when we create an object of SoftwareEngin class, the output will be SoftwareEngineer

class SoftwareEngineer :Employee Reason: Even though there is no construc { public SoftwareEngineer() available in Employee class, a constructor with no-parameter is { automatically supplied to it as a Console.WriteLine("SoftwareEngineer"); default constructor. } }
62

<<Demo : Inheritance and constructors>>

Inheritance and Constructors using 5) (4 of System;

class Employee{ public Employee(int empID){ Console.WriteLine("Employee"); does not get complied. The code } } Reason: class SoftwareEngineer: Employee In Employee class, { the parameter-less constructor public SoftwareEngineer(){ is not available Console.WriteLine("SoftwareEngineer"); automatically will not be supplied explicit constructor is available. } }
63

Discussion: Using the given classes when we create an object of SoftwareEngine Class.

Inheritance and Constructors (5 of 5)


using System;

class Employee{ public Employee(int empID){ Console.WriteLine("Employee"); Instead of the default constructor, } any other constructors of } the base class can be specified fo execution using the base keyword class SoftwareEngineer: Employee { public SoftwareEngineer():base(1001){

Solution: Before executing a child class constructor, the parameter less constructor of the parent class will be automatically executed firs This behavior can be modified.

Console.WriteLine("SoftwareEngineer"); }
}
<<Demo : Inheritance and constructors>>
64

Polymorphism
Refers to an objects ability to behave differently depending on its type
Poly = many morph = form

This characteristic enables making extensions to a classs functionality


Ways achieve polymorphism:
Method Overloading (or Function overloading) Method Overriding (or Function overriding)
65

Method overloading (1 of 3)
More than one methods within the same class having the same name but different method signatures are termed overloaded methods. Calls to overloaded methods will be resolved during compile time.
Also known as static polymorphism

Argument list/ Signature of the method could differ via:


Number of parameters Data type of parameters Sequence of parameters of different data-types

When we write constructors having different signatures, it is nothing but constructor overloading.

66

Method Overloading (2 of 3)
class MathApp { same method name with different method signature public int Add(int a) { return a+10; } public int Add(int a, int b) { return a + b; } public int Add(int a, int b, int c) { return a + b + c; } }
Note: The correct method to be invoked is chosen based on 67 the parameters.

<<Demo : Method overloading>>

Method Overloading (3 of 3)
class MathApp { public int Add(int a) { return a+10; } public float Add(int a) { return a + 20; } }

Compiler Error: Just change in return type alone doesnt mean method overloading
68

Method Overriding (1 of 7)
A subclass can modify behavior inherited from a parent class A subclass can create a method with different functionality than the parents method but with the same:
Name Return type Argument list

The keywords used for method overriding are


virtual new override abstract
69

Method Overriding (2 of 7)
Same method signature in parent and child classes
class Person { public virtual void Print(){ Console.WriteLine("Hi from class Person"); } } class Employee : Person { public override void Print(){ Console.WriteLine("Hi from class Employee"); } }

70

Method Overriding (3 of 7) Multilevel Overriding


override in class Person { employee class, public virtual void Print(){ override extends Console.WriteLine("Hi from class Person"); the Print method } of Person class. } class Employee : Person { public override void Print(){ Console.WriteLine("Hi from class Employee"); } } class SoftwareEngineer : Employee { public override void Print(){ Console.WriteLine("Hi from class SoftwareEngineer"); } }
<<Demo : Method overriding>>
71

Method Overriding (4 of 7) Multilevel Overriding

using System; class Person { public virtual void Print(){ Console.WriteLine("Hi from class Person"); } new - hides the } Print method of class Employee : Person { Person class. public new void Print(){ Console.WriteLine("Hi from class Employee"); } override in } SoftwareEngineer class SoftwareEngineer : Employee { class generates public override void Print(){ error Console.WriteLine("Hi from class SoftwareEngineer"); } Note: } A method to be overridden in a child class should be marked as either virtual or override in the parent class.
<<Demo : Method overriding>>
72

Method Overriding (5 of 7) Multilevel Overriding


using System; class Person { public virtual void Print(){ Console.WriteLine("Hi from class Person"); new virtual hides the Print } method of Person class in } Employee class, but allows class Employee : Person { SoftwareEngineer class to public new virtual void Print(){ override Print method of Employee Console.WriteLine("Hi from class Employee"); } } class SoftwareEngineer : Employee { public override void Print(){ Console.WriteLine("Hi from class SoftwareEngineer"); } }
<<Demo : Method overriding>>
73

Method Overriding (6 of 7) Quiz


using System;

class Person { public override void Print(){ Console.WriteLine("Hi from class Person"); } } class Employee : Person { public override void Print(){ Console.WriteLine("Hi from class Error: Employee"); No virtual method is available for overriding }
}
74

Method Overriding (7 of 7) Sealed Method

class Person { public virtual void Print() { Console.WriteLine("Hi from class Person"); } } class Employee : Person { public override sealed void Print() { Console.WriteLine("Hi from class Employee"); } class SoftwareEngineer : Employee { public override void Print() { Console.WriteLine("Hi from class Software Engineer"); } Error: }

SoftwareEngineer class cannot override Print method of Employee as it is a sealed method

75

Dynamic Method Dispatch (1 of 5)


It is a byproduct of method overriding Understanding of Dynamic Method Dispatch helps to design extendable software To achieve dynamic method dispatch Method overriding is a prerequisite
So, inheritance is also a prerequisite Parent class object reference can point to child/descendant class objects

76

Dynamic Method Dispatch (2 of 5)


The child/descendant class object references can not point to the parent/ancestor class objects A method is called based on the type of the object referred by the reference and NOT based on the type of the reference. This decision is taken at runtime and hence this is known as run time polymorphism

77

Dynamic Method Dispatch (3 of 5)


Using the Person and Employee that are used before, consider the following code snippet
/* Scenario 1 */ Person perObj = new Person(); Employee empObj = new Employee(); perObj.Print();// prints Hi from class person /* Scenario 2 */ Person perObj = new Person(); Employee empObj = new Employee(); perObj = empObj; perObj.Print();// prints Hi from class Employee

The output of perObj.Print(); depends on the object being pointed by perObj at that instant during the runtime.
<<Demo : Dynamic Method Dispatch>>
78

Dynamic Method Dispatch (4 of 4) with a descendant


Consider a scenario
Person class is inherited by Employee class Employee class is inherited by SoftwareEngineer class Each child class has overridden the Print() method of the parent class to print hi from the corresponding class name

Person perObj ; Employee empObj; SoftwareEngineer seObj = new SoftwareEngineer(); empObj = seObj; // parent reference to child object perObj = seObj; // grandparent reference to grandchild object perObj.Print(); // prints Hi from class SoftwareEngineer empObj.Print(); // prints Hi from class SoftwareEngineer

In both the above lines, the object involved is a SoftwareEngineer object

79

Dynamic Method Dispatch (5 of 5)


class Person { public virtual void Print(){} } class Employee : Person { public override void Print(){} public void SayHello(){ /* method logic */ } } Discussion Person perObj; Employee empObj; empObj = new Employee(); perObj = empObj; perObj.Print(); perObj.SayHello(); //Error Fact Dynamic method dispatch is possible only for the methods that are overridden by the child/descendant class.

80

Abstract (1 of 5)
Consider a scenario of the Payroll application. At present, the company has only Technical Evangelist and Software Engineer as employees. The application includes a salary module which calculates the salary based on the role of the employee. The company is thinking of hiring Employees for other roles as well in the future. So the application should be extendible for these category of employees too. To enjoy the extendibility of the application, the need for Dynamic Method Dispatch arises, so the method overriding and so the inheritance.
81

Abstract (3 of 5)
To achieve Dynamic Method Dispatch, we need to have a virtual method in the parent class. In such situations there are circumstances, like GetSalary() method in Employee class, meaningful method body can not be provided to the concerned virtual method. Now we create abstract method, a method declaration with no method body. When an abstract method need to be in a class, that class should be an abstract class.

82

Abstract (4 of 5)
The abstract keyword can be used for method as well as class An abstract method signifies it has no body (implementation), only declaration of the method followed by a semicolon

public abstract double GetSalary();


To implement the method body for GetSalary() in the child class, the override keyword has to be used. That is the child class has to override the abstract method.
83

Abstract (5 of 5)
If a class has one or more abstract methods declared inside it, the class must be declared abstract or an abstract class can be made when a template needs to be described for a group of sub-classes
It must be ensured that no objects require to be created from it

An abstract class cannot be instantiated i.e. objects cannot be created from an abstract class. Reference of an abstract class can point to objects of its sub-classes thereby achieving run-time polymorphism. An abstract class may also have concrete methods, constructors and data members abstract class Employee
{
//Class definition }
84

Abstract Example (1 of 2)

abstract class Employee{ public string SomeMethod() { /* method body */ } public abstract double GetSalary(); } class SoftwareEngineer: Employee{ private string project; public override double GetSalary() { /* method body */ } }
<<Demo : Abstract>>

85

Abstract Example (2 of 2)
abstract class Employee{ public virtual string SomeMethod() { /* method body */ } public abstract double GetSalary(); } class SoftwareEngineer: Employee{ public override string SomeMethod() { /* a new method body */ ERROR } }
<<Demo : AbstractDemo>>
86

The need for interface (1 of 4)


Recall the example used for Dynamic Method Dispatch for achieving extendable software design
HR object

Payroll class
Employee Object reference Any Employees child class object SoftwareEngineer object

What is the intention behind creating the Employee class and inheriting it to HR and SoftwareEngineer classes?

87

The need for interface (3 of 4)


HR and SoftwareEngineer classes can not have two parent classes as C# doesnt allow multiple inheritance Lets pay more attention into purpose of the inheritance demand in this context
Is it for benefiting from methods reusability, by inheriting them from parent class? The answer is NO Is it for achieving extendable software design through Dynamic Method Dispatch? The answer is YES

Under the circumstances of creating a parent class to inherit only for achieving extendable software design through Dynamic Method Dispatch, define the parent as an interface 88 C# allows a class to have many interface parents

The need for interface (4 of 4)


HR object BusinessGuest object Payroll class ECCTracker

Employee

IECCUser

class

Object reference

Object reference

SE object

Intern object
89

Interface (1 of 6) what?
Interface is similar to a pure abstract class that contains only abstract methods The child class has to provide the implementation for all the methods of the interface parent Object of an interface cannot be created. However, object reference of an interface can be created All methods in an interface are public and abstract by default The parent interfaces object reference can point to the object of the child class. Thus providing support to Dynamic Method Dispatch In the inheritance list the class parent should be followed by the interface parents As per the .NET standard, the interfaces name starts with I

90

Interface interface: 6) (2 of Members of an



methods properties indexers events


Constants Fields Operators Constructors Destructors

An interface cannot contain -

All the interface members are public by default Interface can inherit another Interface An interface cannot be instantiated

91

Interface (3 of 6) Right usage


interface IECCUser { /* All the methods of interface are implicitly public and abstract*/ void RegisterUser(); void UnRegisterUser(); } class SoftwareEngineer: IECCUser { public void RegisterUser() { /* implementation is placed here */

} public void UnRegisterUser() { /* implementation is placed here */


<<Demo : Interface>>
92

} }

Interface (4 of 6) wrong usage


interface IECCUser { /* All the methods of interface are implicitly public and abstract*/ void RegisterUser(); void UnRegisterUser(); } class SoftwareEngineer: IECCUser { public void RegisterUser() { /* implementation is placed here */ } }
93

Interface (5 of 6) How to avoid wrong usage


Use refactoring in Visual Studio Right click on interface name which is being implemented by a class and select implement All methods of interface will be added without any explicit business logic implementation

Write your own code inside each method

94

Interface (6 of 6) Dynamic Binding


interface IECCUser { void RegisterUser(); void UnRegisterUser(); } class SoftwareEngineer: IECCUser { public void RegisterUser() { /* implementation */

IECCUser eccUserRef; SoftwareEngineer seObj = new


95

} SoftwareEngineer (); public void eccUserRef = seObj ; UnRegisterUser() {

eccUserRef.RegisterUser();

Avoid name collision (1 of 4)


In the larger projects working with hundreds of classes and interfaces, when a class implements more than one interface there is possibility of name collision To avoid this name collision, we have Explicit Interface Implementation concept For further discussion, let us extend our business scenario

96

Avoid name collision (3 of 4)

HR object BlogTracker class IBlogUser ECCTracker

IECCUser

class

Object reference

Object reference

SE object
97

Avoid name collision (4 of 4)

class SoftwareEngineer: IECCUser, IBlogUser Discussion: { IECCUser eccUserRef; void IECCUser.UnRegister(){ IBlogUser blogUserRef; /* changing the ECCUser SoftwareEngineer seObj; table data */ seObj = new SoftwareEngineer( } void IBlogUser.UnRegister(){ /* call the IECCUser /* changing the BlogUser table data */ implementation */ } eccUserRef = seObj; /* rest of the implementation eccUserRef.UnRegister(); is placed here */ 98 }
/* call the IBlogUser implementation */

Abstract Class vs. Interface design choice


Make use of an abstract class when a template needs to be described for a group of sub-classes
It must be ensured that no objects require to be created from it

Make use of an interface when a role needs to be described for other classes, irrespective of the inheritance tree of these classes

99

Exception Handling (1 of 2)
int val1 = 0; int result = 5/val1; int [] myArray = new int[10]; myArray[1000] = 10;

What happens when the above code snippets are executed ?

Exception is thrown (an object is thrown)


How to recover from this ? (handle it !)
100

Exception Handling (2 of 2)
Exception is thrown by the program on occurring of an error The exception object that is thrown consists of information about the exception, including type of exception and the state of the program when the error occurred. The runtime environment attempts to find the Exception Handler The exception handler tries to recover from the error or if it finds that the error can not be recovered then provides a gentle exit from the program Helpful in separating the execution code from the error handler
101

try-catch-finally
try { // statements } catch( ExceptionType1 et1) { // statements } /* any number of catch block can be used */ catch( ExceptionType2 et2) { //statements } /* optional block. This gets executed irrespective of occurrence of exception */ finally { // statements }
<<Demo : Exception Handling>>
102

Thank You
The contents of this document are proprietary and confidential to Insys Technologies Ltd. and may not be disclosed in whole or in part at any time, to any third party without the prior written consent of Insys Technologies Ltd. 2008 Insys Technologies Ltd. All rights reserved. Copyright in the whole and any part of this document belongs to Insys Technologies Ltd. This work may not be used, sold, transferred, adapted, abridged, copied or reproduced in whole or in part, in any manner or form, or in any media, without the prior written consent of Insys Technologies Ltd.

103

You might also like