Post on 14-Apr-2018
7/27/2019 CS and dot NET
1/80
7/27/2019 CS and dot NET
2/80
Copyright 2003 Compudava
Agenda
Introducing .NET Introducing C# language Basic Data-Access Techniques Developing and Implementing Web
Applications Developing XML Web Services Making the Web Applications
Available to Users
7/27/2019 CS and dot NET
3/80
Copyright 2003 Compudava
OOP and .NET
Programming Techniques OOP concepts Object relationships .NET Overview .NET Architecture
Introducing Assemblies
7/27/2019 CS and dot NET
4/80
Copyright 2003 Compudava
Survey of ProgrammingTechniques
Unstructured Programming Procedural Programming Modular Programming Object-Oriented Programming
7/27/2019 CS and dot NET
5/80
Copyright 2003 Compudava
Unstructured Programming
main program
data
program
Unstructured programming. The mainprogram directly operates on global data.
7/27/2019 CS and dot NET
6/80
Copyright 2003 Compudava
Procedural Programming
Execution of procedures. After processing flow of controlsproceed where the call wasmade.
Mainprogram procedure
Procedural programming. Themain program coordinates callsto procedures and hands over appropriate data asparameters.
main programdata
program
procedure 2 procedure 3procedure 1
7/27/2019 CS and dot NET
7/80Copyright 2003 Compudava
Modular Programming
Modular programming. The main program coordinatescalls to procedures in separate modules and hands over appropriate data as parameters.
main programdata
program
procedure 1
module 1data+data 1
procedure 2 procedure 3
module 2data+data 2
7/27/2019 CS and dot NET
8/80Copyright 2003 Compudava
Modular ProgrammingProblems
Explicit Creation and Destruction
Decoupled Data and Operations Missing Type Safety Strategies and Representation
7/27/2019 CS and dot NET
9/80Copyright 2003 Compudava
Object Oriented Programming
Object-oriented programming. Objects of the programinteract by sending messages to each other.
program
object 2
data
object 3data
object 1data
object 4data
7/27/2019 CS and dot NET
10/80Copyright 2003 Compudava
Object Oriented Concepts
Abstraction Encapsulation
Inheritance Polymorphism
7/27/2019 CS and dot NET
11/80Copyright 2003 Compudava
Objects
Objects are the basic entities in an object-orientedsystem. Each object is denoted by a name andhas state. The variables within the object expresseverything about the object (state) and themethods specify how it can be used (behavior). Amethod is a function or procedure that has accessto the internal state of the object needed toperform some operation.
7/27/2019 CS and dot NET
12/80Copyright 2003 Compudava
Abstraction or HandlingProblems
Problem
Model
Abstraction
The model defines an abstract view tothe problem. This implies that the modelfocuses only on problem related stuff and that you try to define properties of the problem. These properties include:
the data which are affected and the operations which are identified
by the problem.
abstraction is the structuring of a nebulousproblem into well-defined entities by definingtheir data and operations. Consequently,these entities combine data and operations.They are not decoupled from each other.
7/27/2019 CS and dot NET
13/80Copyright 2003 Compudava
Abstract Data Types (ADT)
abstract data type
abstract data structure
operations interfaces
An ADT consists of an abstract data structure and operations.Only the operations are viewable from the outside and define the
interface.
The data structure can only be accessed with definedoperations . This set of operations is called interface and isexported by the entity. An entity with the properties justdescribed is called an abstract data type .
7/27/2019 CS and dot NET
14/80
7/27/2019 CS and dot NET
15/80Copyright 2003 Compudava
Encapsulation
The principle of hiding the used data structure andto only provide a well-defined interface is known asencapsulation.
Encapsulation allows the programmer to presentclearly specified interfaces around the servicesthey provide. The programmer can decide whatshould be hidden and what is intended to bevisible. Some advantages of encapsulation are:
Managing complexity Managing change Protecting data
7/27/2019 CS and dot NET
16/80Copyright 2003 Compudava
Encapsulation
Each class has two parts: An Interface An Implementation.
The Interface is the implementation code for the externalInterface i.e. in the diagram the body of the lion.
The Implementation is the code that does all the operations,makes the interface look as if it is doing something. All thefunctions the lion does such as sleep, eat, hunt etc..)
7/27/2019 CS and dot NET
17/80Copyright 2003 Compudava
Inheritance
As objects do not exist by themselves but are instances of a CLASS, aclass can inherit the features of another class and add its ownmodifications. (This could mean restrictions or additions to itsfunctionality). Inheritance aids in the reuse of code.
Classes can have 'Children' that is, one class can be created out of another class. The original or parent class is known as the SuperClass(or base class). The child class is known as the SubClass (or derivedclass).
7/27/2019 CS and dot NET
18/80Copyright 2003 Compudava
Inheritance
A SubClass inherits all the attributes and behaviors of theSuperClass, and may have additional attributes and behaviors.
7/27/2019 CS and dot NET
19/80Copyright 2003 Compudava
Single inheritance
The attributes and operations in the diagram below are for vehicle class , which the SubClass inherits. Extra operation isthe land vehicle works only on Land and the water vehicle works only in water.
7/27/2019 CS and dot NET
20/80Copyright 2003 Compudava
Multiple inheritance
Multiple inheritance enables the subclass to inherit propertiesof more than one superclass and to merge their properties.
7/27/2019 CS and dot NET
21/80Copyright 2003 Compudava
Polymorphism
Polymorphism means the ability to request that thesame Operations be performed by a wide range of different types of things. Effectively, this meansthat you can ask many different objects to perform
the same action. Same methods in the base class can be called to
perform different actions depending on the run-timecontext.
Client does not worry about how derived class wasinstanced. Usually is done through interface inheritance.
7/27/2019 CS and dot NET
22/80Copyright 2003 Compudava
Summary
To view a program as a collection of interactingobjects is a fundamental principle in object-orientedprogramming. Objects in this collection react uponreceipt of messages, changing their state
according to invocation of methods which mightcause other messages sent to other objects.
Questions?
7/27/2019 CS and dot NET
23/80Copyright 2003 Compudava
Relationships
class Point {attributes:
int x, ymethods:
setX(int newX)getX()setY(int newY)getY()
}
class Circle {attributes:
int x, y, radiusmethods:
setX(int newX)getX()setY(int newY)getY()setRadius(newRadius)
getRadius()
}
Circle Pointa kind of
A-Kind-Of relationship
Knowing the properties of class Point we can describe a circleas a point plus a radius and methods to access it. Thus, acircle is a -kind- of point. However, a circle is somewhat morespecialized.
7/27/2019 CS and dot NET
24/80
Copyright 2003 Compudava
Relationships
Is-A relationship The previous relationship is used at the class level to describe
relationships between two similar classes. If we create objects of two such classes we refer to their relationship as an ``is-a''relationship.
Since the class Circle is a kind of class Point , an instance of Circle , say acircle , is a point . Consequently, each circlebehaves like a point. For example, you can move points in x direction by altering the value of x . Similarly, you move circles inthis direction by altering their x value.
Circle Pointis-a
http://www.desy.de/gna/html/cc/Tutorial/footnode.htmlhttp://www.desy.de/gna/html/cc/Tutorial/footnode.html7/27/2019 CS and dot NET
25/80
Copyright 2003 Compudava
Relationships
Part-Of relationship You sometimes need to be able to build objects by combining them
out of others. You already know this from procedural programming,where you have the structure or record construct to put data of various types together.
Let's come back to our drawing program. You already have createdseveral classes for the available figures. Now you decide that youwant to have a special figure which represents your own logowhich consists of a circle and a triangle. Thus, your logo consists of two parts or the circle and triangle are part-of your logo:
class Logo {
attributes:Circle circleTriangle triangle
methods:set(Point where)
}
Circle Pointpart-of
Logopart-of
7/27/2019 CS and dot NET
26/80
Copyright 2003 Compudava
Relationships
Has-A relationship This relationship is just the inverse version of the part-of
relationship. Therefore we can easily add this relationship to thepart-of illustration by adding arrows in the other direction.
Circle Point
part-of
Logo
part-of
has-of has-of
7/27/2019 CS and dot NET
27/80
Copyright 2003 Compudava
Questions?
7/27/2019 CS and dot NET
28/80
Copyright 2003 Compudava
Introducing .NET Framework
7/27/2019 CS and dot NET
29/80
Copyright 2003 Compudava
Why .NET Framework?
Greater programmer productivity Easier to make Internet software More powerful and sensible
languages Cross-language development The platform scales
7/27/2019 CS and dot NET
30/80
Copyright 2003 Compudava
Microsofts .NET Framework
Multi-language development andexecution environment for softwarecomponents
A strategy for creating, designing, andexecuting applications in a distributedarchitecture
Based on non-proprietary standards Consumer of .NET software can be on
any platform
7/27/2019 CS and dot NET
31/80
Copyright 2003 Compudava
.NET Platform
New Application Programming Interface (API)provides an object-oriented layer on top of Windows.
The .NET platform has been extended to
encompass all the new Windows and Webtechnology from Microsoft including: COM+
Transaction support
ASP .NET Successor to ASP for Web Development
XML Industry standard for extensible markup
Web Services protocol
SOAP, WSDL and UDDI
7/27/2019 CS and dot NET
32/80
Copyright 2003 Compudava
.NET Features
New object-oriented, component-based languages C# Visual Basic .NET
New tools Visual Studio .NET
Includes a comprehensive class library Language platform is designed to support
language independence Program in any language that supports .NET API
Languages are integrated Polymorphism can be implemented across
languages
7/27/2019 CS and dot NET
33/80
Copyright 2003 Compudava
.NET Resources
Common Type System (CTS) makes languageintegration possible
Supported all across of the .NET languages:classes, interfaces, delegates, references type,and value types
Include s Common Language Specification (CLS) Platform sits on the top of the operating system Supports
C# Visual Basic .NET C++ Compiled Jscript.NET CLR provides an object oriented platform
7/27/2019 CS and dot NET
34/80
Copyright 2003 Compudava
.NET Architecture
Common Language Runtime (CLR)
C#Source
C++Source
VB.NETSource
OtherSource
C#Compiler
C++Compiler
VB.NETCompiler
Other Compiler
IL+Metadata IL+Metadata IL+Metadata IL+Metadata
Just-In-Time (JIT) Compiler
Native Code (Managed)
7/27/2019 CS and dot NET
35/80
Copyright 2003 Compudava
IL Intermediate Language
IL+metadata is the output from compilation. IL is an assembly language for a stack-based,
virtual, .NET CPU. IL is similar bytecode emitted by a Java compiler.
IL is fully compiled before it is executed. IL was not designed with a particular programming
language in mind. IL statements manipulate common types shared by
all .NET languages.Common Type System ( CTS) A .NET type ismore than just a data type; .NET types are typicallydefined by classes that include both code and datamembers.
7/27/2019 CS and dot NET
36/80
Copyright 2003 Compudava
CLR and JIT
CLR (Common Language Runtime) is responsible for loadingand executing a .NET application. It employs a JIT (Just-In-Time) compilation to translate the IL to native machine code.
.NET code is always compiled, never interpreted. So .NETdoes not use a virtual machine to execute the program.
Instead, the IL for each method is JIT-compiled when it iscalled for the first time.
The next time the method is called, the JIT-compiled nativecode is executed. The compilation process produces aWindows executable file in portable executable (PE) format.
This has two important implications: First, the CLR neither knows, nor cares, what language was
used to create the application or component. It just sees IL. Second, in theory, replacing the JIT compiler is all thats
necessary to target a new platform.
7/27/2019 CS and dot NET
37/80
Copyright 2003 Compudava
.NET Processes
Windows platform
Common Language Runtime (CLR)
.NET Framework
Data/XML
WebForms
WindowsForms
WebServices
7/27/2019 CS and dot NET
38/80
Copyright 2003 Compudava
Summary
Questions?
7/27/2019 CS and dot NET
39/80
Copyright 2003 Compudava
Assembly Overview
A .NET application is packaged into an assembly , which is a set of one or more files containing types, metadata, and executable code.The .NET documentation describes the assembly as the smallestversionable, installable unit in .NET. It is the functional unit for codesharing and reuse. It is also at the center of .NETs code securityand permissions model. All executable code must be part of an
assembly. When we compile a simple program, the compiler creates anassembly consisting of a single executable file. However,assemblies can contain multiple files including code module filesand files containing resources such as GIF images. Therefore, anassembly can be viewed as a logical DLL.
The assembly contains a manifest that stores metadata describingthe types contained in the assembly, and how they relate to oneanother. The runtime reads this manifest to retrieve the identity of the assembly, its component files and exported types, andinformation relating to other assemblies on which the assemblydepends. When an assembly consists of multiple files, one file will
contain the manifest.
7/27/2019 CS and dot NET
40/80
Copyright 2003 Compudava
Creating a multifile assembly
Suppose we define a Person class using C# and save it tofile called person.cs . We can compile it to a module, asfollows:
csc /target:module /out:person.mod person.cs
The /target:module option tells C# to create a moduletarget. Both C# and Visual Basic .NET compilers support four different types of target output: exe, winexe, library and module
Now, suppose we define a People class using C# whichcreates Person objects and save it to file called people.cs .
csc /addmodule:person.mod people.cs
The /addmodule compiler option is used to link the person.mod module into the People assembly. This givesus a multifile assembly consisting of two module files,
people.exe and person.mod . The assemblys manifest iscontained in people.exe .
7/27/2019 CS and dot NET
41/80
Copyright 2003 Compudava
Creating a multifile assembly
Assembly: People
Module: people.exe
Assembly Manifest
Type Metadata
IL Code
Module: person.exe
Type Metadata
IL Code
7/27/2019 CS and dot NET
42/80
Copyright 2003 Compudava
Day 2. C# Overview
Introduction Identifiers, variables and constants Arrays, types and operators
C# statements Classes, structs and interfaces Delegates and events
Inheritances and Polymorphism Exceptions Examples
7/27/2019 CS and dot NET
43/80
Copyright 2003 Compudava
Introduction
Goal of C# Provide a simple, safe, modern, object-oriented, Internet-
centric, and high-performance language for .NETdevelopment
C# Building blocks language Uses a limited set of keywords and constructs Type-safe language that catches bugs while compiling Builds a lessons in C++ and Java using object-oriented
techniques Language for writing .NET applications The point of learning this language is to build Web and
desktop applications on the .NET platform
7/27/2019 CS and dot NET
44/80
Copyright 2003 Compudava
Structure of a C# programnamespace N1 {
class C1 {// ...
}struct S1 {
// ...}interface I1 {
// ...}delegate int D1();enum E1 {
// ...}
}namespace N2 {
class C2 {public static void Main
( string [] args){
//execution starts here}
}
}
A C# program consists of one or more files, each of which cancontain one or more namespaces,which in turn contain types.
If no namespace is declared, thena default global namespace isassumed.
An executable C# program mustinclude a class containing a Mainfunction member, or method , whichrepresents the program entry pointwhere execution begins. Anycommand-line arguments arepassed as parameters to the Mainmethod in the form of a zero-basedarray of strings.
7/27/2019 CS and dot NET
45/80
Copyright 2003 Compudava
C# Identifiers
An identifier must start with a letter or underscoreand consist of Unicode characters. Typically, anidentifier will consist of letters, underscores, anddecimal digits. C# identifiers are case sensitive.
You cannot use a C# keyword as an identifier.However, you may prefix an identifier with the @character to distinguish it from a keyword:object @this;
// prevent clash with "this" keyword
7/27/2019 CS and dot NET
46/80
Copyright 2003 Compudava
C# Variables
A C# variable represents a location in memory where an instance of some type is stored. There are no global variables in C#. Valuetypes can be directly declared and initialized. C# has two methodsfor ensuring that variables are initialized before use: Variables that are fields in a class or struct, if not initialized
explicitly, are by default zeroed out when they are created.
Variables that are local to a method must be explicitly initializedin your code prior to any statement in which their values areused. In this case, the initialization doesnt have to happen whenthe variable is declared, but the compiler will check all possiblepaths through the method and will flag an error if it detects anypossibility of the value of a local variable being used before it isinitialized.
bool bln = true;char ch1 = 'x';decimal d1 = 1.23M;double dbl1 = 1.23;short sh = 22;int i = 22;
long lng1 = 22;sbyte sb = 22;float f = 1.23F;ushort us1 = 22;uint ui1 = 22;string s = "Hello";
7/27/2019 CS and dot NET
47/80
Copyright 2003 Compudava
C# Constants
C# provides the const modifier which can be used in front of adeclaration to create program constants:
const int min = 1;
const int max = 100;
const int range = max - min;
Constants are typically initialized with a literal value. Theycan also be given the value of an expression, as we do withthe range constant above, provided that the compiler canevaluate the expression at compile time. Therefore, thefollowing would generate a compiler error because the value
of the expression assigned to i cannot be known until runtime:System.Random r = new System.Random();
const int i = r.Next(1, 7);
//error - compiler cannot evaluate
7/27/2019 CS and dot NET
48/80
Copyright 2003 Compudava
C# Arrays
Arrays in C# are zero-based and, for the most part, work like they doin other common programming languages. The array type is areference type.
string [] a;string []a1 = new string [1000];string [] a2 = {cat,dog,mouse}; int [,] b3 = {{3,4},{4,7},{6,4}};int [][] matrix = new int [3][];matrix[0] = new int [] {1, 2, 3};matrix[1] = new int [] {1, 2, 3, 4, 5};matrix[2] = new int [] {1, 2};object [] ar = {3,"cat,2.45}; string animal = ( string )ar[1];
You cannot change the size of an array once it has beeninstantiated (other than by copying the contents to a new array). If you want to dynamically add elements to an array, you will have tocreate an instance of the ArrayList object, which is in theSystem.Collections namespace.
7/27/2019 CS and dot NET
49/80
Copyright 2003 Compudava
C# Predefined Data Types
C# has two categories of data type: Value types Reference types
Conceptually, the difference is that a valuetype stores its value directly, while areference type stores a reference to thevalue.
Value types are stored in an area known asthe stack.
Reference types are stored in an areaknown as the managed heap .
7/27/2019 CS and dot NET
50/80
Copyright 2003 Compudava
Value vs. reference types
Value Types{
int i=3;int j=i;
} Reference Types{
string s=hello; string t=s;
}
i 3
j 3
s
t
h
el
l
o
stack
stack
heap
7/27/2019 CS and dot NET
51/80
Copyright 2003 Compudava
Integer types
Name CTS Type Description Range (min:max)
sbyte System.SByte 8-bit signed integer -128:127 (-2 7:27-1)
short System.Int16 16-bit signed integer -32,768:32,767 (-2 15:215-1)
int System.Int32 32-bit signed integer -2,147,483,648:2,147,483,647(-2 31:231-1)
long System.Int64 64-bit signed integer -9,223,372,036,854,775,808: -9,223,372,036,854,775,808(-2 63:263-1)
byte System.Byte 8-bit unsigned integer 0:255 (0:2 8-1)
ushort System.UInt16 16-bit unsigned integer 0:65,535 (0:216
-1)uint System.UInt32 32-bit unsigned integer 0:4,292,967,295 (0:2 32-1)
ulong System.UInt64 64-bit unsigned integer 0:18,446,744,073,709,551,615(0:2 64-1)
7/27/2019 CS and dot NET
52/80
Copyright 2003 Compudava
Floating Point, Decimal, Boolean,Character and Reference Types
Name CTS Type Description SignificantFigures
Range (min:max)
float System.Single 32-bit single-precisionfloating-point
7 1.5 10 -45 to 3.4 1038
double System.Double 64-bit double-precisionfloating-point
15/16 5.0 10 -324 to 1.7 10308
decimal System.Decimal 128-bit high precisiondecimal notation
28 1.0 10 -28 to 7.9 1028
Name CTS Type Values
bool System.Boolean true or false
char System.Char Represents a single 16-bit (Unicode) chatacter
Name CTS Type Description
object System.Object The root type, from which all other types in the CTS derive(including value types)
string System.String Unicode character string
7/27/2019 CS and dot NET
53/80
Copyright 2003 Compudava
C# Operators
Category Operator
Arithmetic + - * / %Logical & | ^ ~ && || !String concatenation +Increment and decrement ++ --
Bit shifting >Comparison == != < > =
Assignment = += -= *= /= %= &= |= ^= =Member access (for objects and structs) .Indexing (for arrays and indexers) []Cast ()Conditional (the Ternary Operator) ?:Object Creation newType information sizeof (unsafe code only) is typeof asOverflow exception control checked uncheckedIndirection and Address * -> & (unsafe code only) []
7/27/2019 CS and dot NET
54/80
Copyright 2003 Compudava
checked and unchecked
are used to control overflow checking in arithmetic operationsand conversions . Example1:byte b=255;
checked
{b++;
}
Console.WriteLine
(b.ToString());
When we try to run this, we willget an error message like this:Arithmetic operationresulted in an overflow.
Example2:byte b=255;
unchecked
{b++;
}
Console.WriteLine
(b.ToString());
In this case, no exception will beraised, but we will lose data since the byte type cant hold avalue of 256, the overflowing bitswill be discarded, and our bvariable will hold a value of zero
unchecked
is the default
7/27/2019 CS and dot NET
55/80
Copyright 2003 Compudava
is, sizeof and typeof
The is operator allows us to check whether an object is compatible with aspecific type (an object is either of that type or is derived from that type)Example:
int i=10;if (i is object ){
Console.WriteLine("i is an object");}
We can determinate the size (in bytes) required by a value type on the stackusing the sizeof operator Example:
unsafe{
Console.WriteLine( sizeof ( int ));}
The typeof operator returns a Type object representing a specified type.This is useful when we want to use reflection to find out information about anobject dynamicallyExample:
Console.WriteLine( typeof ( string ));
7/27/2019 CS and dot NET
56/80
Copyright 2003 Compudava
Boxing and Unboxing
Boxing and unboxing allow us to convert value types toreference types and vice versa. Boxing is the term used to describe the transformation of a
value type to a reference type. Unboxing is the term used to describe the reverse process,
where the value of a reference type is to a value type.Example:int i = 20;object o = i; // Box the intint j = ( int )o; // Unbox it back into an int
When unboxing, we have to be careful that erceving valuevariable has enough room to store all the bytes in the valuebeing unboxed. C#s int s, for example, are only 32 bits long,so unboxing a long value (64 bits) into an int as shownbelow will result in an InvalidCastException :
long a = 333333423;object b = ( object )a;int c = ( int )b;
7/27/2019 CS and dot NET
57/80
Copyright 2003 Compudava
C# statements
C# statements are similar C, C++ or Java statements, excepting switch statement: C# provides the gotocase and goto default , to allowmultiple cases to execute the samestatement block. Omitting the break statements causes a compiler error.
Also C# introducing the foreach statement:
foreach ( int temp in arrayOfInts)
{ Console.WriteLine(temp);}
We cant change the value of theitem in the collection ( temp above)
uint i = 2;
switch (i) {
case 0:
goto case 1;
case 1:
goto case 2;case 2:
Console.WriteLine("i3");
break ;
}!
7/27/2019 CS and dot NET
58/80
Copyright 2003 Compudava
C# Class definition
The fundamental building block of a C# application is the class .[attributes] [modifiers] class identifier [:base-list] { class-body }[;] Where: attributes (Optional) Additional declarative information. modifiers (Optional) The allowed modifiers are new ,
abstract , sealed , and the four access modifiers ( public ,protected , internal , private ). The access levelsprotected and private are only allowed on nested classes.
identifier The class name. base-list (Optional) A list that contains the one base class
and any implemented interfaces, all separated by commas. class-body Declarations of the class members (Constructors,
Destructors, Constants, Fields, Methods, Properties, Indexers,Operators, Events, Delegates, Classes, Interfaces, Structs).
7/27/2019 CS and dot NET
59/80
Copyright 2003 Compudava
C# Class members
Classes contain Data members and Function members Data members are those members that contain the datafor the class fields, constants, and events.
Function members are those members that contain code methods, constructors, properties, and operator overloads
Methods The syntax for defining and invoking a method in C# is virtually
identical to the syntax in C++ and Java. Arguments can ingeneral be passed into methods by reference, or by value. Avariable that is passed by reference to a method is affected byany changes that called method makes to it, while a variable thatis passed by value to a method is not changed by any changesmade within the body of the method. Since reference types onlyhold a reference to an object, they will still only pass thisreference into the method. Value types, in contrast, hold theactual data, so a copy of the data itself will be passed into themethod.
7/27/2019 CS and dot NET
60/80
Copyright 2003 Compudava
Access Modifiers
Access modifiers are keywords used to specify the declaredaccessibility of a member or a type. There are four accessmodifiers: public , protected , internal , private .
public access is the most permissive access level. There areno restrictions on accessing public members.
A protected member is accessible from within the class inwhich it is declared, and from within any class derived from theclass that declared this member. A protected member of abase class is accessible in a derived class only if the accesstakes place through the derived class type.
internal members are accessible only within files in the
same assembly. private access is the least permissive access level. Private
members are accessible only within the body of the class or thestruct in which they are declared. Nested types in the same bodycan also access those private members.
7/27/2019 CS and dot NET
61/80
Copyright 2003 Compudava
Constructors A constructor is a method that is invoked upon instantiation of a class. We
declare a method that has the same name as the containing class, andwhich does not have any return type.
If you dont explicitly supply any constructor, the compiler will just make adefault one up for you behind the scenes. Itll be a very basic constructor that
just initializes all the member fields to their normal default values (emptystring for strings, zero for numeric data types, and false for bool s).
You can provide as many overloads to the constructor as you wish, providingthey are clearly different in signature.
If you supply any constructors that take parameters, then the compiler willnot automatically supply a default one.
It is possible to define constructors as private or protected. This is useful intwo situations:
If your class serves only as a container for some static members or properties, andtherefore should never be instantiated; If you want the class to only ever be instantiated by calling some static member
function.
If you declare only one or more private constructors, you will also make itimpossible for any class derived from your class to ever be instantiated byany means whatsoever.
ll f h
7/27/2019 CS and dot NET
62/80
Copyright 2003 Compudava
Calling Constructors from Other Constructors
You may sometimes find yourself in the situation where you haveseveral constructors in a class, perhaps to accommodate someoptional parameters, for which the constructors have some code incommon. For example, both constructors initialize the same fields
class Car {
private string description;
private uint nWheels;
public Car( string description, uint nWheels)
{
this .description = description;
this .nWheels = nWheels;
}public Car( string description)
{
this .description = description;
this .nWheels = 4;
}
}
class Car {
private string description;
private uint nWheels;
public Car( string description, uint nWheels)
{
this .description = description;
this .nWheels = nWheels;
}public Car( string description):
this (description,4)
{
}
}
7/27/2019 CS and dot NET
63/80
Copyright 2003 Compudava
Method Overloading
C# supports method overloading, which allows aclass , struct , or interface to declare multiplemethods with the same name, provided thesignatures of the methods are all different.Constructor methods can be overloaded too.
C# does places some minimum differences on theparameters of overloaded methods: It is not sufficient for two methods to differ only in their
return type
It is not sufficient for two methods to differ by virtue of aparameter having been declared as ref or out .
7/27/2019 CS and dot NET
64/80
Copyright 2003 Compudava
Method Overriding and Hiding
By declaring a base class function asvirtual
, we allow the function tobe overridden in any derived class. In C#, functions are not virtual by default, but (aside from
constructors) may be explicitly declared as virtual .
C# differs from C++ syntax, however, because it requires you toexplicitly declare when a derived classs function override s another
function, using override keyword. If a method with the same signature is declared in both base and
derived classes, but the methods are not declared as virtual andoverride respectively, then the derived class version is said to hide the base class version. The result is that which version of a method getscalled depends on the type of the variable used to reference the
instance, not the type of the instance itself. In most cases you wouldwant to override methods rather than them, because hiding themgives a strong risk of the wrong method being called for a given classinstance. In C#, we should use the new keyword to declare that weintend to hide a method.
7/27/2019 CS and dot NET
65/80
Copyright 2003 Compudava
Inheritance
C# allows us to design a class by using inheritance toembrace and extend an existing class. C# supports onlysingle inheritance.
C# supports the concept of a universal base class,System.Object , from which all other classes are ultimatelyderived. If you do not specify a base class in your classdefinition, the C# compiler will assume that System.Object is the base class.
A class inherits the members of its direct base class.Inheritance means that a class implicitly contains all membersof its direct base class, except for the instance constructors,destructors and static constructors of the base class.
A derived class can hide inherited members by declaring newmembers with the same name or signature. Note however that hiding an inherited member does not remove thatmember it merely makes that member inaccessible directlythrough the derived class.
7/27/2019 CS and dot NET
66/80
Copyright 2003 Compudava
Interfaces
An interface may inherit from multiple base interface s,and a class or struct may implement multipleinterface s.
An interface can be a member of a namespace or aclass and can contain signatures of the following members:
Methods, Properties, Indexers, Events An interface can inherit from one or more base
interface s. interface s can contain methods, properties, events, and
indexers. The interface itself does not provide
implementations for the members that it defines. Theinterface merely specifies the members that must besupplied by class es or struct s that implement theinterface .
When a class base list contains a base class andinterface s, the base class comes first in the list.
7/27/2019 CS and dot NET
67/80
Copyright 2003 Compudava
C# Interface definition
An interface defines a contract. A class or struct thatimplements an interface must adhere to its contract.[attributes] [modifiers] interface identifier [:base-list]
{interface-body}[;] Where: attributes (Optional) Additional declarative information. modifiers (Optional) The allowed modifiers are new and the
four access modifiers ( public , protected , internal ,private ).
identifier The interface name. base-list (Optional) A list that contains one or more explicit
base interface s separated by commas. interface-body Declarations of the interface members.
7/27/2019 CS and dot NET
68/80
Copyright 2003 Compudava
C# Properties
Properties are an extension of fields and are accessed using thesame syntax. Unlike fields, properties do not designate storagelocations. Instead, properties have accessors that read, write, or compute their values.
[attributes] [modifiers] type identifier { accessor-declaration } [attributes] [modifiers] type interface-type .identifier { accessor-declaration }
Where: attributes (Optional) Additional declarative information. modifiers (Optional) The allowed modifiers are new , static ,
virtual , abstract , override , and a valid combination of thefour access modifiers.
type The property type, which must be at least as accessible asthe property itself. identifier The property name. accessor-declaration Declaration of the property accessors, which
are used to read and write the property. interface-type The interface in a fully qualified property name.
7/27/2019 CS and dot NET
69/80
Copyright 2003 Compudava
The Object Class
Supports all classes in the .NET Framework class hierarchyand provides low-level services to derived classes. This is theultimate base class of all classes in the .NET Framework; it isthe root of the type hierarchy.
In C#, if you dont specify that a class is derived from another
class, the compiler will automatically assume that it derivesfrom Object. The practical significance of this is that, besides the methods
and properties and so on that you define, you also haveaccess to a number of public and protected member methodsthat have been defined for the Object class. These methods
are available in all other classes that you define.
7/27/2019 CS and dot NET
70/80
Copyright 2003 Compudava
Object Class members
Method Access Modifiers Pupose
string ToString() public virtual Returns a string representation of the object
int GetHashTable() public virtual Used if implementing dictionares(hash tables)
bool Equals( object obj) public virtual Compares instances of the objectforequality
bool ReferenceEquals( object objA, object objB)
public static Compares instances of the objectfor equaity
Type GetType() public Returns details of the type of theobject
object MemberwiseClone() protected Makes a shallow copy of the object
void Finalise() protected virtual This is the .NET version of adestructor
7/27/2019 CS and dot NET
71/80
Copyright 2003 Compudava
The out and ref keyword C# provides ref and out parameters to enable value types to be
passed by reference. Use the ref keyword to specify that aninitialized value should be passed by reference. The ref keywordmust be used both in the call and in the method signature.
The ref keyword is used to allow the modification, by a method, of an existing initialized variable. If, instead, the method assigns theinitial value to the variable, you should use the out keyword.
void Increment( ref int i){
i++;}...int i = 0; // initializedIncrement( ref i);// now i==1
void Increment( out int i){
i=5;}...int i; // uninitializedIncrement( out i);// now i==5
Also, i must first be initializedbefore being passed as a parameter to Increment.
7/27/2019 CS and dot NET
72/80
Copyright 2003 Compudava
static Constructors
One novel feature of C# is that it is also possible to write a static no-parameter constructor for a class. Such a constructor will only ever beexecuted once, as opposed to the constructors weve written so far,witch are instance constructors, and executed whenever an object of that class is created.
One reason for writing a static constructor would be if your class hassome static fields or properties that need to be initialized from anexternal source before the class is first used.
The .NET runtime makes no guarantees about when a static constructor will be executed. In C#, the static constructor usually seems to beexecuted immediately before the first call to a member of the class.
The static constructor does not have any access modifiers, cannot ever take any parameters, can only access static members, and there canonly ever be one static constructor for a class.
It is possible to have a static constructor and zero-parameter instanceconstructor defined in the same class. Although the parameter lists areidentical, there is no conflict here because the static constructor isexecuted when the class is loaded, but the instance constructor isexecuted whenever an instance is created.
7/27/2019 CS and dot NET
73/80
Copyright 2003 Compudava
C# struct definition A struct type is a value type that can contain constructors,
constants, fields, methods, properties, indexers, operators,events, and nested types
[attributes] [modifiers] struct identifier [:interfaces] body [;] Where: attributes (Optional) Additional declarative information.
modifiers (Optional) The allowed modifiers are new and thefour access modifiers ( public, protected, internal, private ). identifier The struct name. interfaces (Optional) A list that contains the interfaces
implemented by the struct , all separated by commas. body The struct body that contains member declarations.
Differences between classes
7/27/2019 CS and dot NET
74/80
Copyright 2003 Compudava
Differences between classesand structs
Struct s are value types, not reference types. This meansthey are stored either in the stack or inline (if they are part of another object that is stored on the heap), and have the samelifetime restrictions as the simple data types.
Struct s do not support inheritance. The only exceptions tothis is that struct s, in common with every other types in C#,derive ultimately from the class System.Object and haveaccess to the methods of System.Object , and it is evenpossible to override them in struct s.
There are some differences in the way constructors work for struct s. In particular, the compiler always supplies a defaultno-parameter constructor, which you are not permitted toreplace.
With a struct , you can (if you wish) specify how the fieldsare to be laid out in memory.
7/27/2019 CS and dot NET
75/80
Copyright 2003 Compudava
abstract Modifier The abstract modifier can be used with classes, methods,
properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a
class is intended only to be a base class of other classes. Abstractclasses have the following features: An abstract class cannot be instantiated.
It is not possible to modify an abstract class with the sealed modifier,which means that the class cannot be inherited. A non-abstract class derived from an abstract class must include actual
implementations of all inherited abstract methods and accessors. Use the abstract modifier in a method or property declaration to
indicate that the method or property does not contain
implementation. Abstract methods have the following features: An abstract method is implicitly a virtual method. Abstract method declarations are only permitted in abstract classes. Because an abstract method declaration provides no actual
implementation, there is no method body It is an error to use the static or virtual modifiers in an abstract
method declaration.
7/27/2019 CS and dot NET
76/80
Copyright 2003 Compudava
sealed Modifier
A sealed class cannot be inherited. It is anerror to use a sealed class as a base class. Usethe sealed modifier in a class declaration toprevent inheritance of the class.
It is not permitted to use the abstract modifier witha sealed class. Struct s are implicitly sealed; therefore, they
cannot be inherited.
7/27/2019 CS and dot NET
77/80
Copyright 2003 Compudava
Operator Overloading C# allows user-defined types to overload operators by defining static
member functions using the operator keyword. Where you might want to write overloads for operators?
From the world of mathematics, almost any mathematical object:coordinates, vectors, matrices, functions, and so on.
Graphics programs will also use mathematical or coordinate-relatedobjects when calculating positions on screen.
A class that represents an amount of money A word processing or text analysis program might have classes
representing sentences, clauses, and so on, and you might wish to useoperators to combine sentences together (a more sophisticated versionof concatenation for strings).
Which Operators Can You Overload?Category Operators Restrictions
Arithmetic binary +, *, /, -, % none Arithmetic unary +, -, ++, -- noneBitwise binary &, |, ^, noneBitwise unary !, ~, true , false none
Comparison ==, !=, >, >=,
7/27/2019 CS and dot NET
78/80
Copyright 2003 Compudava
C# Indexers Indexers permits your classes to be treated as arrays. An indexer is
a member that enables an object to be indexed in the same way asan array. Whereas properties enable field-like access, indexersenable array-like access.
[attributes ] [modifiers ] indexer-declarator {accessor-declarations }Where:
attributes (Optional) Additional declarative information. modifiers (Optional) Allowed modifiers are new, virtual, sealed,
override, abstract, extern , and a valid combination of the four access modifiers.
indexer-declarator Includes the type of the element introduced by theindexer, this , and the formal-index-parameter-list .
type A type name. accessor-declarations The indexer accessors, which specify the
executable statements associated with reading and writing indexer elements.
identifier The parameter name
Indexers Accessor
7/27/2019 CS and dot NET
79/80
Copyright 2003 Compudava
Indexers Accessor Declaration
get Accessor The get accessor body of an indexer is similar to a method body. It
returns the type of the indexer. The get accessor uses the sameformal-index-parameter-list as the indexer. For example:
get{
return myArray[index];}
set Accessor The set accessor body of an indexer is similar to a method body. It
uses the same formal-index-parameter-list as the indexer, inaddition to the value implicit parameter. For example:
Set{
myArray[index] = value ;}
7/27/2019 CS and dot NET
80/80
C# Delegates A delegate declaration defines a reference type that can be used
to encapsulate a method with a specific signature. A delegateinstance encapsulates a static or an instance method.
[attributes ] [modifiers ] delegate result-type identifier ([formal- parameters ]);
Where: attributes (Optional) Additional declarative information. modifiers (Optional) The allowed modifiers are new and the
four access modifiers . result-type The result type, which matches the return type
of the method.
identifier The delegate name. formal-parameters (Optional) Parameter list. If a parameter
is a pointer, the delegate must be declared with the unsafemodifier.