net framework.net framework is a software framework that can be installed on windows operating...

69
.NET Framework • .NET framework is a software framework that can be installed on Windows operating system • It includes library of coded solutions to common programming problems and a common language infrastructure that manages the execution of programs written specifically for framework • .NET framework supports several programming languages which allows language interoperability, whereby each language can utilize code written in other languages • Programs written in .NET framework execute in a software environment that manages the programs runtime requirement

Upload: hubert-turner

Post on 16-Jan-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Framework• .NET framework is a software framework that can be

installed on Windows operating system• It includes library of coded solutions to common

programming problems and a common language infrastructure that manages the execution of programs written specifically for framework

• .NET framework supports several programming languages which allows language interoperability, whereby each language can utilize code written in other languages

• Programs written in .NET framework execute in a software environment that manages the programs runtime requirement

Page 2: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Framework• The Framework Base Class Library provides– User Interface– Data Access– Database Connectivity– Cryptography– Web Application Development– Numeric Algorithms– Network CommunicationsThis class library is used by the programmers to combine it with their own code to produce applications

Page 3: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Framework

Visual C#. NET

User

Visual C++ .NET Visual Basic .NET Visual J# .NET

Microsoft Intermediate Language (MSIL)

Common Language Runtime (CLR)

Native Code Computer

Page 4: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Framework• Programs written in .NET Framework execute in a software

environment that manages the programs runtime requirements

• This runtime environment is known as Common Language Runtime(CLR).

• The CLR provides the appearance of an application virtual machine so that programmers need not consider the capabilities of specific CPU

• The CLR provides important services such as security, memory management, exception handling

• The class library and CLR together form the .NET Framework• The primary role of CLR is to locate, load and manage .NET

types, manage memory, creating application domain etc

Page 5: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Framework• The CTS (Common Type System) is another building block of .NET

platform• It fully describes all possible data types and programming

constructs supported by the runtime • The CLS (Common Language Specification) contains definition of

subset of common types and programming constructs that all .NET programming languages agree on

• .NET platform provides a base class library that is available to all .NET programming languages

• It contains various threads, file I/O, graphical rendering and interaction with various devices and support for services required by most real world applications

• The following diagram shows the structures of base class libraries and CLR

Page 6: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Framework

Base Class Libraries Common Language Runtime (CLR)

Common Type System (CTS)

Common Language Specification (CLS)

Database Access

Desktop GUI APIs

Web APIs

File I/O

Threading

Remote APIs

Security

Page 7: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Core C# Features• No pointers required• Automatic memory management through garbage collection• Formal syntactic constructs for classes, interfaces, structures, enumerations and

delegates• C++ like ability to overload operators• Support for attribute based programming• Ability to build generic types and generic members• Support for anonymous methods which allow us to apply an inline function anywhere a

delegate type is required• Ability to define single type across multiple code files using partial keyword• Support for strongly typed queries(LINQ – Language Integrated Query) used to interact

with various forms of data • Support for anonymous types which allow us to model the shape of a type rather than

its behaviour• Ability to extend the functionality of an existing type using extension methods• Inclusion of lambda operator(=>) which simplifies working with delegate types• A new object initialization system which allows to set property values at the time of

object creation

Page 8: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Features• Interoperability - .NET Framework provides means to access

functionality that is implemented in programs that execute outside the .NET environment

• Common Runtime Engine – The CLR is the execution engine of .NET Framework. All .NET programs execute under the supervision of the CLR guaranteeing certain properties and behaviors in the areas of memory management, security and exception handling

• Language Independence – The .NET Framework introduces CTS that define all possible data types and programming constructs supported by CLR and how they may or may not interact with each other

• Base Class Library – The Base Class Library (BCL) is a library of functionality available to all languages using the .NET Framework. The BCL provides classes which encapsulate a number of common functions like reading and writing, graphic rendering, database interaction etc.

Page 9: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Features

• Simplified Deployment – The .NET Framework includes design features and tools that help manage the installation of computer software to ensure that it does not interfere with previously installed software

• Security – The design is meant to address some of vulnerabilities exploited by malicious software

• Portability – The design of the .NET Framework allows it to theoretically be platform independent and thus cross platform compatible

Page 10: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Assembly• .NET binaries take the file extensions like .dll or .exe • .NET binaries do not contain platform specific instructions,

but IL and type metadata• When a .dll or .exe is created using .NET compiler the

resulting module is bundled into an assembly• An assembly contains CIL code which is similar to Java byte

code that is not compiled into platform specific instructions until necessary

• Assemblies are stored in the Portable Executable (PE) format, common on the Windows platform for all dll and exe files

• Assemblies also contains metadata that describes the characteristics of every type within the binary

• CIL is self describing through .NET metadata

Page 11: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Assembly• The CLR checks the metadata to ensure that the correct

method is called• Metadata is generated by compilers but developers can

create their own metadata through custom attributes• Metadata contains information about the assembly and

is used to implement programming capabilities of .NET• CIL and type metadata, assemblies themselves are also

described using metadata termed as manifest• The manifest contains the information about the

current version of the assembly, culture information and a list of all externally referenced assemblies that are required for proper execution

Page 12: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Benefits Of CIL (Common Intermediate Language)

• Language Integration - .NET aware compiler produces identical CIL instructions hence all languages are able to interact within a well defined binary arena

• CIL is platform uncertain, the .NET Framework is also platform uncertain providing the same benefits Java developers have accustomed to

• There is an international standard for the C# language and a large subset of the .NET platform

Page 13: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

CIL Compile To Platform Specific Instructions

• Since assemblies contain CIL instructions rather than platform specific instructions CIL code must be compiled before use

• The entity that compiles the CIL code into meaningful CPU instructions is termed as JIT (Just In Time) compiler

• The .NET runtime environment controls a JIT compiler for each CPU

• As JIT compiler compiles CIL instructions into corresponding machine code it will cache results in memory in a manner suited to the target OS

Page 14: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Metadata

• .NET assembly contains metadata which describes each and every type as well as members of each type.

• Metadata is used by numerous aspects of the .NET runtime environment

• Metadata is also used by various object browsing utilities, debugging tools and C# compiler itself

Page 15: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

.NET Common Language Runtime(CLR)

• Runtime is a collection of external services required to execute a given compiled unit of code. For eg. JVM for Java etc

• .NET platform occurs a runtime system that provides a single well defined runtime layer that is shared by all languages and platforms that are .NET aware

• The core of CLR is represented by a library called mscoree.dll• When an assembly is referenced for use mscoree.dll is loaded

automatically which in turn loads the required assembly into memory• The runtime engine is the entity in charge of resolving the location of

an assembly and finding the requested type within the binary by reading the contained metadata

• The CLR also interacts with the types contained in the .NET base class libraries when required

• The base class libraries contains large number of core types that encapsulate s a wide variety of common programming tasks

Page 16: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Common Type System (CTS) And Common Language Specification (CLS)

• The .Net framework provides multiple language support using the feature known as Common Type System that is built into CLR.

• The CTS supports a variety of types and operation found in most programming languages and therefore calling one language from another does not require type conversions

• The Common Language Specification defines a set of rules that enables interoperability on the .Net platform

• These rules serve as a guide to third party compilers designers and library builders.

• The CLS is a subset of CTS and therefore the language supporting the CLS can use each others class libraries as if they are their own

Page 17: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Microsoft Intermediate Language (MSIL) And Managed Code

• It is an instruction set into which all the .Net programs are compiled.

• It is akin to assembly language and contains instructions for loading, storing initializing and calling methods

• When a C# program is written the source code is compiled into MSIL

• The code that satisfies the CLR at runtime in order to execute is referred to as managed code

• Compilers that are compatible to the .Net platform generate managed code

• The managed code generated is the IL code which is then converted to native machine code by the JIT compilers

Page 18: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Platform Independent .NET• .NET assemblies can be developed and executed also on non

Microsoft OS because of CLI (Common Language Infrastructure)• The CLI is a set of standards that ties all components of .NET

Framework into a cohesive and consistent system• It lays out the concepts and architecture of the system and

specifies the rules and convention to which all software must adhere

• The CTS (Common Type System) define the characteristics of the types that is used in the code

• The CTS defines a rich set of intrinsic types with fixed, specific characteristics for each type

• The CLS (Common Language Specification) specifies rules, properties and behaviors of .NET compliant programming language

Page 19: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Introduction To C#

• C# is a new language created by Microsoft• C# is a powerful and flexible programming language• C# is designed to support the key features of .NET

Framework• C# is fully object oriented and component oriented

language• C# simplifies and modernizes C++• C# is a simple modern language that directly addresses

the needs of component-based software development• C# is a language for NGWS(Next Generation Windows

Services) applications

Page 20: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Characteristics Of C#• Elegant Object Oriented Design• Safety and Productivity• Namespaces• Security• Garbage Collection• Data Types• Versioning• Indexers• Exception Handling• Error Elimination• Flexibility and Power• Extensibility Interoperability

Page 21: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Applications Of C#

• Console Applications• Windows Applications• Developing Windows Controls• Developing ASP.NET projects• Creating Web Controls• Providing Web Services• Developing .NET Component Library

Page 22: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Difference Between C++ And C#• C++ was designed to be low level platform neutral object

oriented programming language. C# was designed to be a somewhat higher level component oriented language

• C++ code usually compiles to assembly language. C# compiles to Intermediate Language (IL) which is subsequently converted to native executable code by JIT compiler

• With C# the garbage collector periodically comes in and scans through the references in your code in order to identify which areas of heap are currently used by our program and then removes the objects that are no longer in use

• The condition in each if and else if must evaluate to bool. For eg. If(x){….} not allowed instead if(x!=0){…..}

• C# provides as additional control flow statement, foreach

Page 23: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Differences Between C++ and C#• In C# a switch statement may not fall through to the next statement if it does any

work. Thus switch(i) {

case 1:func1();

case 2:func2();

} will not workTo do this task

switch(i){

case 1:func1();goto case 2:

case 2:}

Page 24: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Differences Between C++ and C#• New control flow statement “foreach” loops across all the items in

array or collection without requiring explicit specification of the indices

foreach( int I in MyArray){

System.Console.WriteLine(i);}

• Boxing is like any other casting in which contents of the variable will be copied to heap and a reference is created. To unbox a value simply cast it back to its original type. The usual reason for boxing is to pass a value to a method that accepts a reference type as parameter

• In C# structs are very different from classes. Structs in C# are designed to encapsulate lightweight objects. They are value types and hence passed by values. They are sealed which means they cannot be derived from any base class

Page 25: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Differences Between C++ and C#• Simple types and structs are value types while all classes are

reference types. Value types hold value on the stack like variables while reference types hold address of an object on the heap like pointers. Value types are passed to methods by value while reference types are passed by reference

• In C# classes do not have an access modifier on the name of the base class. Inheritance is always public. A class can be derived from only one class. If no base class is specified then class will be automatically derived from System.Object C# permits the declaration delegates, events and properties. Two extra modifiers are available internal and protected internal

Page 26: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Differences Between C++ and C#• C# implements different programming model for destructors due to garbage

collection• Virtual methods must be overriddenClass Base{

protected int a;public Base(int a){ this.a=a; }public virtual void Show(){ System.Console.WriteLine(“Base A”+a); }

}Class Derived:Base{

int b;public Derived(int a,int b):Base (a){ this.b=b; }public override void Show(){ System.Console.WriteLine(“Base A” +a);

System.Console.WriteLine(“Derived B=“ +b);}

}

Page 27: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Differences Between C++ and C#• C# requires definite assignment that is all variables must be

initialized before used or out keyword must be used to pass uninitialized variable

• There is no conversion between the bool type and other types• C# defines finally block which contains code that is always executed

at the end of try block irrespective of whether any exception was thrown. The finally block is executed as soon as control leaves a catch or try block and contains clean up code. C# requires that the exception be a class derived from System.Exception

• C# contains delegates that can hold reference to a method. A delegate class has a signature and it can hold references only to methods that match it signature

Page 28: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Differences Between C++ and C#• In C# properties are first class members of classes. To

the client a property looks like a member variable but to the implementer of the class it looks like method

• C# provides inherent support for metadata. Attributes are supplied by CLR or by creating for own purpose. CLR attributes support serialization and COM interoperability. Custom attributes provide additional information about program elements

Page 29: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Differences Between Java And C#• C# includes more primitive types and functionality to catch

arithmetic exceptions• Includes a large number of notational conveniences such as

operator overloading and user defined casts• Event handling is a part of language itself• Allows the definition of structs which are similar to classes but

may be allocated on the stack• C# implements properties as part of the language syntax• C# allows anonymous methods providing closure functionality• C# allows iterator that employs co-routines via a functional

style yield keyword• C# has support for output parameters aiding in return of

multiple values • C# has the ability to alias namespace

Page 30: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Differences Between Java And C#• C# has Explicit Member Implementation which allows a class to

specifically implement methods of an interface, separate from its own class methods

• C# provides integration with COM• C# allows call by reference for primitive and reference types• Javas strictfp keyword guarantees that the result of floating point

operations remain the same across platforms• Java supports checked exceptions for better enforcement of error

trapping and handling• Javas lack of support for unsigned numeric types makes it somewhat

unsuited for low-level programming• C# does not include checked exceptions• C# includes delegates they simplify the code by removing the need to

declare new classes• Java requires that a source file name must match the only public class

inside it while C# allows multiple public classes in the same file

Page 31: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Differences Between Java And C#• C# allows the use of pointers and goto keyword• C# has true multidimensional arrays as well as

arrays of arrays called jagged arrays• Java does not include operator overloading• Methods in C# are non virtual by default whereas

in Java methods are virtual by default

Page 32: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

A Sample C# Programusing System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace ConsoleApplication1{ //this is a sample C# program /* It shows the structure the comments type and the various inputs and data types and printing etc.*/ class FirstProgram { static void Main(string[] args) { int a, b, c; Console.Write("Enter a value for a : "); a = Convert.ToInt16(Console.ReadLine()); Console.Write("Enter a value for b : "); b = Convert.ToInt16(Console.ReadLine()); c = a + b; Console.WriteLine("Sum of " + a + " and " + b + " is " + c); Console.ReadKey(); } }}

Page 33: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Description Of C# Program• The using statement contains the names of namespaces being used in

this entire program• The next line declares the namespace which contains the class to be

created• The next lines contains the comments for the program which are

– // Single Line Comment– /* */ Multi Line Comment

• The next line contains the class which is a template for an object• C# is a block structured language means code blocks are always

enclosed in braces { and }• The next line defines the Main method which is the starting point of

the program. Any C# application can contain only one Main method• The next line declares the variables and then with the help of

conversion methods like Convert.ToInt32() the values from the keyboard are accepted using the Console.ReadLine() method.

• The output is then displayed using Console.WriteLine () method

Page 34: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Accessing Data Through Command Line Arguments

• Click on Project menu and select project properties from it

• Select Debug option from the left side panel and enter the data in the Command Line Arguments box.

• The arguments must be separated by space or by Enter key

• The values can then be displayed using args keyword array where the array index starts from 0 (zero)

Page 35: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

C# KeywordsAbstract As Base Bool Break Ulong Unit

Byte Case Catch Char Event Value While

Explicit Extern False Finally Fixed Set Readonly

Float For Foreach Namespace New Short Ref

Null Object Operator Out Override Unchecked Return

Params Private Static String Struct Virtual Sbyte

Switch This Throw True Try Sizeof Sealed

Typeof Checked Class Const Continue Unsafe Using

Decimal Default Delegate Double Do Volatile

Else Enum Get Goto If Stackalloc

Implicit In Int Interface Internal Ushort

Is Lock Long Protected Public Void

Page 36: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Literals

C# Literals

Numeric Literals

Integer Literals Real Literals

Boolean Literals

Character Literals

Single Character

LiteralsString Literals

Page 37: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Literals Contd.• Literals are the value constants assigned to a variable

(or results of expressions) in a program• C# supports several types of literals– Integer Literals – An integer literal refers to a sequence of

digits. There are two types of integers decimal(0 to 9) and hexadecimal (digits preceded by 0x or 0X)

– Real Literals – These are digits that contain fractional or floating point numbers. A real literal may also be expressed in exponential (or scientific) notation. A floating point literal may thus comprise four parts• A whole part• A fractional part • A decimal point• An exponent

Page 38: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Literals Contd.– Boolean Literals – There are two Boolean literal values

TRUE and FALSE. They are used as values of relational expressions

– Single Character Literals – A single-character literal or a character constant contains a single character enclosed within a pair of single quote ‘X’ ‘4’

– String Literals – A string literal is a sequence of characters enclosed between double quotes. The characters may be alpha bets, digits, special characters and blank spaces like “Hello C#”, “Well Done”,”?.... !”

– Backslash Character Literal – C# supports some backslash character literals like ‘\n’, ‘\a’,’\r’

Page 39: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Variables And Data Types• A variable is an identifier that denotes a storage

location used to store a data value. • A variable may take different values at different

types during the execution of a program• Every variable has a type that determines what

values can be stored in that variable• Every variable in C# is associated with a data type

that specify the size and type of values that can be stored.

• The types in C# are primarily divided into Value Types and Reference Types

Page 40: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

C# Data Types

C# Data Types

Value Types

Predefined Types

Integers

Real Numb

ers

Booleans

Characters

User Defin

ed Types

Enumeratio

ns

Structures

Pointers

Reference Types

Predefined Types

Objects

Strings

User Defin

ed Types

Classes

Delegates

Arrays

Interfaces

Page 41: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Decision Making And Looping• While statement –

While (condition){

Body Of The Loop}

• Do statement -do{

Body Of The Loop} (condition);

• For statement – for(initialization; condition;increment / decrement) {

Body Of The Loop }

Page 42: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Decision Making And Looping• Foreach statement –

foreach (type variable in expression){

Body Of The Loop}

public static void main(){

int[] a = {11,22,33,44};foreach ( int m in a){

Console.WrilteLine(“ “ +m);}

}

Page 43: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Decision Making And Looping• Break And Continue statement –

while (condition){

if(condition)break;

}while (condition){

if(condition)continue;

}

Page 44: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Structures And Enumerations• Structures often referred as structs is a unique way of packing together data of different

data types• It is a convenient tool for handling a group of logically related data items • It creates a template that may be used to define its data properties• Structs are declared using struct keyword as follows• struct struct-name {

Data member1;Data member2;

}After the structure is declared a variable can derived from it through which the members of the structure are accessible

struct-name variable-name;OR

struct-name variable-name = new struct-name();variable-name.struct-member-name=value;

• A struct variable is initialized to its default values of its members as soon as it is declared• Structs members are private by default and therefore cannot be accessed outside the

structure definition. To make it available outside use the public keyword

Page 45: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Structures And Enumerations• As data members are private they can be accessed through methods or constructors• C# permits declaration of structures inside another structuresStruct Employee{

public string name;public int code;public struct Salary{

public double basic;public double allowance

}}

ORStruct M{

public int x;}Struct N{

public M objM;public int y;

}Accessing elements

N objN;n.m.x=100;n.y=200;

Page 46: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Differences Between Classes And StructsCategory Classes Structs

Data Type Reference type and therefore stored on the heap

Value type and therefore stored on stack. Behaves like simple data types

Inheritance Support Inheritance Do not support inheritance

Default Values Default value of a class type is null

Default value is the value produced by zeroing out the fields of the struct

Field Initialization Permits initialization of instance fields

Do not permit initialization of instance fields

Constructors Permits declaration of parameter less constructors

Do not support parameter less constructors

Destructors Supported Not supported

Assignment Assignment copies the reference

Assignment copies the values

Page 47: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Structures And Enumerations• An enumeration is a user defined integer data type which provides a way for attaching names to numbers.• The enum keyword automatically enumerates a list of words by assigning them values 0, 1, 2 and so on.• The syntax of enum isenum Color {Red, Green, Yellow, Blue}

ORenum Color{

Red,Green,Blue

}• We may also assign specific values to enum membersenum Color{

Red=1.Green =3,Yellow=5,Brown,Blue=Red+3

}• By default the type of enum is int but we can change it as followsenum Color:long{

Red,Green,Blue

}

Page 48: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Classes And Objects• All object oriented languages employ three core

principles• Encapsulation – ability to hide internal details of an

object from its users. Implemented by using access modifier keywords public, private and protected

• Inheritance – is the concept to build new classes using existing class definition. The original class is called as base class or parent class and new class is called as derived class or child class

• Polymorphism is the ability to make more than one form

Page 49: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Defining Class And Objectsclass classname{

variable declaration;methods declaration

}classname object = new classname();ORclassname object;object = new classname();object.methodname();

Page 50: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Constructors• Methods that have the same name as that of the class and are

called explicitly and declared with public modifier• Types of constructors

– Default Constructors – It is created without any arguments in braces– Parametrized Constructors – It is created with parameters inside the

braces. These parameters can be used to initialize variables declared inside the class

– Static Constructors – Called before any object is created– Copy Constructors – Creates an object by copying variables from

another object• Destructors – Same features as constructor but prefixed with

~ (tilde symbol)• C# supports keyword this which is a reference to the object

that has called that method

Page 51: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Access ModifiersModifier Accessibility Control

Private Only within the class containing the member

Public Anywhere outside the class as well as inside and derived class

Protected Visible only to its own class and derived class

Internal Available within the assembly or component that is being created but not to the clients of that component

Protected internal Containing program or assembly and in the derived classes

Page 52: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Static Members• Members declared with static keyword are called as static

members.• Since these members are associated with the class itself rather

than with individual objects• The static variables and methods are often referred to as class

variables and class methods • Static variables are used when we want to have a variable

common to all instances of a class.• Static methods are also called using without any objects• Static methods have following restrictions

– Can call other static methods– Can access only static data– Cannot refer to this or base in any way

• A static constructor is called before any object is created and it cannot have any parameters

Page 53: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common
Page 54: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Inheritance And Polymorphism• Inheritance represents a kind of relationship

between two classes• In this feature one class is created from another class• The created class is called derived class or child class

and the other class is called base class or parent class• The types of inheritance are– Single (One base one derived)– Multiple (Several base classes and one derived class)– Multilevel (Derived from a derived class)– Hierarchical (One base class and several derived classes)

• Multiple not implemented directly but through interfaces

Page 55: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Defining Inheritanceclass subclass-name : baseclass-name{

Body of the class;}Characteristics Of Inheritance– A derived class can extend its direct base class . It can

add new members to those it inherits but cannot change the definition of an inherited member

– Constructors and destructors are not inherited– A derived class can hide an inherited member– A derived class can override an inherited member

Page 56: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Method Overriding• Method inheritance enables us to define and use

methods repeatedly in subclasses• Method overriding is possible by defining a method

in sub class that has the same name and same arguments and same return type as method in superclass

• Then when that method is called the method defined in subclass is invoked and executed instead of one in the superclass provided that– The method in the base class must be specified with

keyword virtual– The method in the subclass using the keyword override

Page 57: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Operator Overloading

• Operator overloading means an existing operator is made to work with user defined data types

• For example a (+) binary arithmetic operator can be used to add two strings etc.

• Overloadable operators include binary, unary, bitwise binary, unary bitwise, logical operators, conditional, compound assignment

• When we overload a binary operator to compound assignment equivalent is implicitly overloaded

• Logical operators must be overloaded in pairs means == and != must be done together

• Operators that are currently not defined in C# cannot be overloaded

Page 58: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Need For Operator Overloading• Operator overloading helps us to generate more

readable and intuitive code in number of situations– Mathematical or physical modeling where we use

classes to represent objects such as coordinates, vectors, matrices etc

– Graphical programs where coordinate related objects are used to represent positions on screens

– Financial programs where a class represents an amount of money

– Text manipulation where classes are used to represent strings and sentences

Page 59: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Defining Operator Overloading• To define an additional task to an operator we must

specify what it means in relation to the class to which the operator is applied

• This is done with the help of special method called operator method which describes the task. The general form of operator method ispublic static retval operator op(arglist){

Method body;}

• The operator is defined in much the same way as method except that we tell compiler it is actually an operator we are defining by the operator keyword followed by the symbol op

Page 60: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Key Features Of Operator Methods• They must be defined as public and static• The retval (return value) type is the type that we get

when we use this operator• The arglist is the list of arguments passed. The

number of arguments will be one for the unary operators and two for binary operators

• In case of unary operators the argument must be the same type as that of the enclosing class or struct

• In case of binary operators the first argument must be of the same type as that of the enclosing class or struct and the second may be of any type

Page 61: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Properties• C# provides a mechanism called properties that has the same

capabilities as accessor methods but is more elegant and simple to use

• Using a property a programmer can get access to data members as though they are public fields

• The class declares a property and then defines a get accessor method also known as getter and a set accessor method also known as setter

• The getter method uses the keyword return to return the fields value to the caller.

• The setter method uses the keyword value to receive the value being passed in from the user

• The type of value is determined by the type of property• As the name implies getter is used to get values or read and setter

is used to set values or write

Page 62: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Properties

• A property can omit either a get clause or set clause • A property that has only getter is called read only

property and the property that has only setter is called write only property which is rarely used

• The get clause uses code to calculate the value of the property using other fields and returns the results

• Properties are inheritable • Static modifier cab be used to declare properties that

belong to the whole class rather than to a specific instance of a class

Page 63: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Indexer• Indexers are location indicators and are used to access class objects

just like accessing elements in an array• An indexer looks like a property and is written like a property but

with following differences– Indexer takes an index argument and looks like an array– The indexer is declared using the name this

• Indexer and properties differ in the following ways– Property can be static member whereas an indexer is always an instance

member– Get accessor of a property corresponds to a method with no parameters

where as get accessor of an indexer corresponds to a method with same formal parameter list as the indexer

– Set accessor of a property corresponds to a method with single parameter named value where as set accessor of an indexer corresponds to a method with the same formal parameter list as the indexer plus a parameter named value

– It is an error for an indexer to declare a local variable with the same name as an indexer parameter

Page 64: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Operation Polymorphism• It is implemented using overloaded methods and

operators• The overloaded methods are selected for invoking by

matching arguments in terms of number, type and order

• This information is known to the compiler at the time of compilation and therefore the compiler is able to select and bind the appropriate method to the object for a particular call at the compile time itself

• This process is called early binding or static binding or static linking or compile time polymorphism

Page 65: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Inclusion Polymorphism• It is achieved through the use of virtual functions• Assume class A implements a virtual method M

and classes B and C that are derived form A override the virtual method M

• When B is cast to A, a call to method M from A is dispatched to B. Similarly when C is cast to A a call to M is dispatched to C

• The decision on exactly which method to call is delayed until runtime and therefore it is also known as runtime polymorphism or dynamic binding or late binding or dynamic linking

Page 66: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Interface Multiple Inheritance• An interface contains one or more methods, properties, indexers

and events but none of them are implemented in the interface itself

• It is the responsibility of the class that implements the interface to define the code for implementation of these members

• Syntax interface <interface name>{

Member declaration}

• Interfaces can also be extended as followsinterface name2:name1{

Members of name2}

Page 67: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Interface Multiple Inheritance

• Interfaces are used as superclasses whose properties can be inherited by clases as follows

class classname : interfacename{

Body of the class}class classname : superclass,

interface1,interface2…{

Body of the class}

Page 68: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Explicit Interface Implementation• One of the main reasons that C# does not support

multiple inheritance is the problem of name collision. Example

interface I1 {void Display();}interface I2 {void Display();}class C1 : I1,I2{

public void Display{ }}

• C# supports a technique known as explicit interface implementation which allows a method to specify explicitly the name of the interface it is implementing

Page 69: NET Framework.NET framework is a software framework that can be installed on Windows operating system It includes library of coded solutions to common

Managing Errors And Exceptions