dot net along with c#
TRANSCRIPT
-
7/29/2019 Dot Net Along With C#
1/181
-
7/29/2019 Dot Net Along With C#
2/181
Index
Introduction to OOPS
Oops Concept
Introduction to C# Dot Net Framework
Literals and Data Types
Branching and Looping Constructor
Inheritance
Abstract Class Interface
Delegates
Events Structure
Arrays
Enumerator Collections
Exception Handling
Sealed Class
Files
Generics
-
7/29/2019 Dot Net Along With C#
3/181
-
7/29/2019 Dot Net Along With C#
4/181
Introduction
Classes And Object
OOPS Concepts
Advantages
Contents:
-
7/29/2019 Dot Net Along With C#
5/181
INTRODUCTION
Object-Oriented Programming allows programmers to use the
same terminology to explain the business domain and the
program.
OOPenables users to model real-world objects. Modeling
means representing real-world objects as components.
-
7/29/2019 Dot Net Along With C#
6/181
Explanation
Before OOP, programmers used to creating computer
applications using procedural-programming (or structure-programming)
In procedural- programming all the program functionalitywritten in a few modules of code or maybe one module(depending on the program).
These modules depend on one another and maybe if youchange a line of code you will have to rewrite the wholemodule again and maybe the whole program.
The introduction of OOP, solved lots of problems ofprocedural programming.
In oops codes are written in independent parts calledclasses. Each program functionality is divided into classes.The assembly combines these classes to form a singleprogram.
Now if any changes has to be made then that particular orspecific class is taken and necessary changes is to be made.
-
7/29/2019 Dot Net Along With C#
7/181
CLASS & OBJECT
The single entity holding the data and methods is
called a class. An Objectis an instance of a
class.
Eg: Car is a class and engine is an object.
People is a class and Mary is an object.
A class is a plan from which many objects can be
created.
-
7/29/2019 Dot Net Along With C#
8/181
Suppose that someone builds a paper pattern for a shirt. All the
shirts done with the same paper pattern will be identical (samedesign, size, etc.). In this sample, the paper pattern is the class
and the shirt is the object. To build the same exact shirt over
and over, you need the paper pattern as a template.
Paper Patternis the Class
And
Shirtis the Object
-
7/29/2019 Dot Net Along With C#
9/181
OOPS CONCEPTS
Polymorphism
Encapsulation
Abstraction
Inheritance
-
7/29/2019 Dot Net Along With C#
10/181
INHERITANCE
Inheritance creates a hierarchy of classes and helps you
reuse the code of a parent class in a child class.
A Class inherits the attributes and behavior of its parent
class or superclass.
Superclass: Base class: Parent class.
Subclass: Derived class: Child class.
The mechanism of constructing one class from an other
class is called Inheritance.
-
7/29/2019 Dot Net Along With C#
11/181
Syntax: class extends
The Shape class is the
parent class. Square,
Rectangle, and Circle are
derived classes that inherit
from Shape.
class declaration class
child: parent
class Square: Shape
Shape
Circle Rectangle
Triangle
-
7/29/2019 Dot Net Along With C#
12/181
ENCAPSULATION
Encapsulation hides internal implementation details from
users.
Internal details, such as data representation should not be
accessible externally, this protects outside users frommaking internal changes.
There is visibility to the functionalities offered by an object,
and no visibility to its data.
Encapsulation means hiding of non-essential details.
-
7/29/2019 Dot Net Along With C#
13/181
EXAMPLE
When a user selects a command from a menu in an
application, the code used to perform the actions of that
command is hidden from the user.
A Customer may issue a check and now know how it isprocessed. The internal processing is hidden from the
customer.
-
7/29/2019 Dot Net Along With C#
14/181
ABSTRACTION
Abstraction means representing of essential
details.
An abstract class is a parent class that allowsinheritance but can never be instantiated.
Abstract classes contain one or more abstract
methods that do not have implementation.
-
7/29/2019 Dot Net Along With C#
15/181
A Shape class, which is anabstract class. In the realworld, you never calculatethe area or perimeter of ageneric shape, you mustknow what kind ofgeometric shape you havebecause each shape (eg.square, circle, rectangle,
etc.) has its own area andperimeter formulas.
People own savingsaccounts, checkingaccounts, credit accounts,investment accounts, but
not generic bank accounts.In this case, a bankaccount can be an abstractclass and all the otherspecialized bank accountsinherit from bank account.
TriangleRectangle
Circle
Shape
-
7/29/2019 Dot Net Along With C#
16/181
POLYMORPHISM
Polymorphism means one entity existing in multiple forms.
The design principle used in this is the same message sent to
different objects results in different behavior.
Even though classes are derived or inherited from the same
parent class, each derived class will have its own behavior.
-
7/29/2019 Dot Net Along With C#
17/181
EXAMPLE
All of them are shapes andas shapes their area andperimeter can becalculated; however, eachshape calculates its area in
a specialized way. In the same way Every key
of a keyboard performs aspecific action when akeystroke message isgenerated for that key.
However, by usingpolymorphism, the samecode with a small changecan be used by differentkeys of the keyboard totrigger specific actions.
Shape
CircleArea=3.14*r*r
(r=Radius)
RectangleArea=H*W
(H=height,
W=width)
SquareArea=4*S*S
(S=side)
-
7/29/2019 Dot Net Along With C#
18/181
Advantages
Enables the use of real-world modeling .
- Any real world object is considered as an object.
Promotes the reuse of code.
-By the use of inheritance etc, coding in a single class can be
used many times.
Provides flexibility in the modification of an existingapplication .
-If any changes in a single line code, only that specific class
is taken and made necessary changes.
Helps with the maintainability of code.
-You can create classes for different types of organization.
- This helps in maintaining data information separately.
-
7/29/2019 Dot Net Along With C#
19/181
-
7/29/2019 Dot Net Along With C#
20/181
Introduction
What Lead to C#
Features in C#
Characteristics in C#
Contents:
-
7/29/2019 Dot Net Along With C#
21/181
C#
C# (pronounced "C sharp") is a programming language that isdesigned for building a variety of applications that run on the
.NET Framework.
C# is simple, powerful, type-safe, and object-oriented.
Delegates, Interface, Foreach Statements, Enumerations arefew features in C# which lag in C++.
The first component oriented language in the C/C++ family
-
7/29/2019 Dot Net Along With C#
22/181
What lead C#
C/C++ Drawbacks:
Poor type safety. High complexity of language.
Memory leakage.
Weak in consistency.
Visual Basic Drawbacks:
Truly not Object- Oriented.
Also could not meet the requirements ofWorld Wide Web.
Java Drawbacks:
Lacking in inter-operability with code of other languages.
TrulyObject-Oriented but does not feature like OperatingOverloading.
Hence keeping in view of these drawbacks, The Microsoft wantednew language that will suite the requirements ofWorldWide WebApplication. Hence, Lead to the Introduction of c#( pronounced "C
sharp").
-
7/29/2019 Dot Net Along With C#
23/181
Productivity of
Visual Basic,
Power of
C++
and Elegance of
Javacombines to form C#.
C# is the combination of
70% ofJava,
10% ofC++,
5% ofVisual Basicand 15% newfeatures.
New Features:
Boxing/UnBoxing.
For each Statements.
Go to.
Events
Delegates
Interfaces
Rectangular Arrays
-
7/29/2019 Dot Net Along With C#
24/181
Characteristics of c#:
Object Oriented
Garbage Collection
Namespace
Data Types
Inter Operability
Versionable
Security
Indexes
Exception Handling
Data Types
-
7/29/2019 Dot Net Along With C#
25/181
-
7/29/2019 Dot Net Along With C#
26/181
Introduction
DotNet Architecture
Common Language Runtime
Base Class Library
DotNet Framework Services
DotNet Execution Model
C# and DotNet
Contents:
-
7/29/2019 Dot Net Along With C#
27/181
Dot Net Framework
C# is mainly dependent for supporting the key features of dotnet framework.
The dot net framework provides an environment for building,deploying and running web services and other applications.
This is the working platform for applications.
-
7/29/2019 Dot Net Along With C#
28/181
Dot Net Framework Architecture
VB C++ C# JAVA .
Common Language Specification
ASP. NET
Web forms, Web Services
ADO.NET and XML
Base Class Library
Common Language Runtime
Window Forms Visual
Studio
Dot
NET
-
7/29/2019 Dot Net Along With C#
29/181
Common Language Runtime
Common Language Runtime:
-its a runtime engine which manages the runtime code (c#application).
-is a part of dot net framework.
Simplify Application Development, Deployment and
Management.
Managed code:
-a code that satisfies the CLR.
-
7/29/2019 Dot Net Along With C#
30/181
Common Language Runtime
Program written in any DOT NET language
(C#,VB.Net etc)
Intermediate Language (IL)
(.exe or .dll)
Common Language Runtime
Loads and Executes code
Compiler
Compiler
-
7/29/2019 Dot Net Along With C#
31/181
-
7/29/2019 Dot Net Along With C#
32/181
Common Type System:
-Defines rules that languages must follow, which helps ensurethat objects written in different languages can interact with
each other.
-is responsible for interpreting the data types into the common
format - e.g. how many bytes is an integer.
Common Language Specification:
-This ensure inter-operability between Languages.
-All the rules that apply to the common type system apply to
the CLS, except where stricter rules are defined in the CLS.
-
7/29/2019 Dot Net Along With C#
33/181
IL Compiler:
-takes in the IL code and converts it to the host machinelanguage.
Security:
-ensures that the assembly (the program being executed) has
permissions to execute certain functions.
Garbage collector:-Its function is to reclaim the memory when the object is no
longer in use, this avoids memory leaks and dangling
pointers.
Class loader:
-Its sole purpose is to load the classes needed by theexecuting application.
-
7/29/2019 Dot Net Along With C#
34/181
.Net Framework Services
ASP.NET:
-Its a server side scripting technology.
Web Forms:
-Manageable code
Window Forms:
-Framework for building rich controls.
ADO.Net:
-Used as connectivity( e.g.: datasets)
-XML support.
-
7/29/2019 Dot Net Along With C#
35/181
.NET Base Class Libraries
System
System.Data System.Xml
System.Web
Globalization
Diagnostics
Configuration
Collections
Resources
Reflection
Net
IO
Threading
Text
ServiceProcess
Security
Design
ADO
SQLTypes
SQL
XPath
XSLT
Runtime
InteropServices
Remoting
Serialization
Serialization
Configuration SessionStateCaching Security
Services
Description
Discovery
Protocols
UIHtmlControls
WebControls
System.Drawing
ImagingDrawing2D
TextPrinting
System.WinFormsDesign ComponentModel
-
7/29/2019 Dot Net Along With C#
36/181
Base Class Library
The Framework Class Library or FCL nothing short of a
massive collection of classes, structures, enumerated types
and interfaces defined and implemented for reuse in your
managed software.
If you like, you can use it like any other library.
That is to say that you can write applications that make use
of the objects in the Base Class Library to read files, display
windows, and do various tasks.
The FCL is a class library; however it has been designed for
extendibility and compose ability. This is advanced reuse.
-
7/29/2019 Dot Net Along With C#
37/181
Visual Studio .NET
.NET
Platform
Manage
andCollaborate
Deployment
Testing
Development
Design
Analysis
Planning
Visual Studio is an
integrated
development environment
published by Microsoft for
writing Windows programs.
.NET can also be used to
write managed applications
in C#, C++, Visual Basic and
any other language
Visual Studio .NET and the
.NET Framework as different
products.
-
7/29/2019 Dot Net Along With C#
38/181
.Net Execution
VB C# C++
complier compliercomplier
assembly assembly assembly
Common Language Runtime / Just-In-Time Complier
Operating system service
Managedcode Managedcode Managedcode Unmanagedcode
Source
code
Nativecode
MSIL
CLR Service
Compilation
Execution
-
7/29/2019 Dot Net Along With C#
39/181
Assembly:
-Logical unit of deployment, also contains metadata, MSIL
and resources.
Microsoft Intermediate Language (MSIL or IL):-CPU independent language.
Metadata:
-Structured Information (class or method definition,
properties etc).
Managed Code:-Any code that targets the CLR.
-Any .Net Language ,including c# ,c++, Visual Basic etc.
JIT-Complier:
-All managed code runs in native Language. Operating System:
-your working system.
-
7/29/2019 Dot Net Along With C#
40/181
Sample
using System; //Namespace
declarationclass Sample //class
Declaration
{
static void Main() //method
{
Console.write(Hello);
}
}
OUTPUT:
Hello
The compilation saved with .csextension which in this case is
Sample.cs
Namespace:
-elements designed to help youorganize the program.
-avoid clashes between two sets ofcode.
Class Declaration:
-contains data and methodsdefinition that you use in your
program.Method:
-It tells what this class will do whenexecuted.
-Main, is always considered as entrypoint.
Outlet:
-console is a class in systemnamespace.
-and write is a method in consoleclass.
-the (.)separates subordinateelements.
-namespace.class.method=pattern
-
7/29/2019 Dot Net Along With C#
41/181
-
7/29/2019 Dot Net Along With C#
42/181
Literals
Data Types
Reference And Value Type
Boxing And Unboxing
Contents:
-
7/29/2019 Dot Net Along With C#
43/181
Literals
Literals are value constants assigned to variables .C# supports several types
of literals.
Boolean
True or False
String
Sequence of Character. Eg: HELLO.
Character
Single Character, Simple-escape Sequence like below
Eg:a , \a \\r \
Real
Decimal Digits, Sign like +,-.
Integer
Decimal Digits, Hexadecimal Digits like below
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
Literals
Boolean
Integer
Character
String
Real
-
7/29/2019 Dot Net Along With C#
44/181
Data Types
Integer: Int , uint 32-bit,
Long , ulong 64-bit,
Short , ushort 16-bit,
Sbyte , byte 8-bit.
Floating Point:
Float 32-bit,
Double 64 bit.
Charactar and String: Char 16-bit unicode
String-set of unicode
Type Conversionint i = 5;
double d = 3.2;
strings = 432;
Implicit conversion d = i;
Cast required i = (int)d;
Conversion required
i = System.Convert.Toint32(s);
V l A d R f T
-
7/29/2019 Dot Net Along With C#
45/181
Value And Reference Type
Value Type
Directly contain data.
Allocated on Stack.
Eg: Structs,Enums
Reference Type
Contains reference to object.
Allocated on Heap using new keyword.
Eg:Classes,Interface
Ex:
int a=1;
Ex:
object ob=a
-
7/29/2019 Dot Net Along With C#
46/181
Boxing And UnBoxing
Converting value type to reference type is called Boxing.
Converting reference to value type is called UnBoxing.
Eg: int a=1; //boxing
object ob=a;
int j=(int)ob; //unboxing
-
7/29/2019 Dot Net Along With C#
47/181
-
7/29/2019 Dot Net Along With C#
48/181
Methods
Kinds of Methods
Properties
Contents:
-
7/29/2019 Dot Net Along With C#
49/181
Methods
Any class has methods and properties.
These are the places where business logic or functionally is
written and executed.
Method is declared as:
Return-type methodname ( Parameterslist );
Example: Int Addition(intx,int y){}
Int--- Return-type
Addition---methodname
Int x,int y---parameters list
-
7/29/2019 Dot Net Along With C#
50/181
There are two kinds of method:
Instance method:This method is called by creating object of that class
which contains the method.
Static Method:
This method is called by the classname in which the
method is located. We should use the keyword static
for this method.
Syntax: Classname.methodname();
We can declare the signature of the same method once
again in the same class but with different parameters.
The parameters should be different.This is calledmethod overloading.
Kinds Of Methods
-
7/29/2019 Dot Net Along With C#
51/181
Methods
using Systems;
class Intsmethod
{
void show()
{
int x=100;
int y=200;
Console.WriteLine(x);Console.WriteLine(y);
}
static void Main()
{
Intsmethod a=new Intsmethod();
a.show();}
}
using System;
class Statemethod{
static void show()
{
int x=100;
int y=200;
Console.WriteLine(x);
Console.WriteLine(y);
}
static void Main()
{
Statemethod.show();}
}*100
200
*100
200
-
7/29/2019 Dot Net Along With C#
52/181
Methods with Two Parameters
using System;
class Twopara
{void show(int a, int b)
{
Console.WriteLine(a);
Console.WriteLine(b);
}
static void Main(){
Twopara t=new Twopara();
t.show(200,300);
}
}
Using System;
Class Overloadmet
{Void show(int a)
{
Console.WriteLine(a);
}
Void show(int a, int b)
{Console.WriteLine(a);
Console.WriteLine(b);
}
Static void Main()
{
Overloadmet o=new Overloadmet();
o.show(2);o.show(5,9);
}
}
*200
300
*2
*5
9
-
7/29/2019 Dot Net Along With C#
53/181
Properties
Properties provide added functionality to the .Net
framework. In c# property consists of
1. Field Declaration
2. Accessor method(get and set methods)
{get{}set{}
}
Get() is used to retrieve a field value and Set() is used to
modify fields value. If you want to make the property read-only, omit the set
block and to make it write only, omit the get block.
This is a secured manner to pass the data.
-
7/29/2019 Dot Net Along With C#
54/181
Properties
Example:
Using System;Class Propertyex
{
Public string id;
Public string Idvalue
{
Get{
Return value;
}
Set
{
id=value;}
}
Static void Main()
{Propertyex pe=new Propertyex();
pe.id=007;
String p=pe.id;
Console.WriteLine(The Value is{0},p);
}}
OUTPUT:
007
-
7/29/2019 Dot Net Along With C#
55/181
7
6
5
43
2
1
0
-
7/29/2019 Dot Net Along With C#
56/181
If-Else Statements
Switch Statements
While Statements
Do-While Statements
For Statements
Foreach Statements
Contents:
-
7/29/2019 Dot Net Along With C#
57/181
IF-Else Statements
The first Selection Statements ifstatementhas three forms:
1. Single Selection.
2. Ifthen - else Selection.
3. Multi - case Selection.
Syntax:
if( condition1 )
//statement
else if( condition2 )
//statement
else(condition)
//statement
Class elseifsample
-
7/29/2019 Dot Net Along With C#
58/181
p
{
Static void Main()
{
Console.Writeline(WRITE A NUMBER);
Int i=Convert.Toint32(Console.ReadLine());If(i>0 && i
-
7/29/2019 Dot Net Along With C#
59/181
Switch Statements
The second Selection is Switchcase statements The value is compared to each of case statements untill
match is found.
Syntax:
switch( value )case result1:
statement1;
break;
case result2:
statement1;
break;
default:
statement1
Class SwitchState
{
-
7/29/2019 Dot Net Along With C#
60/181
{
static void Main()
{
string k;
int i, j;
Console.WriteLine(Select two numbers);i= Convert.ToInt32(Console.ReadLine());
j= Convert.ToInt32(Console.ReadLine());
Console.WriteLine(Select operator +,-,*);
k= Convert.ToChar(Console.ReadLine());
switch (k)
{
case+:Console.WriteLine({0}+{1}={2},i , j,+(i+j));
break;
case-:
Console.WriteLine({0}-{1}={2},i ,j,+(i-j));
break;
case*:
Console.WriteLine({0}*{1}={2},i ,j,+(i*j));
break;
default:
Console.WriteLine(Invalid operator {0},k);
break;
}
}
}
Select two numbers
23
Select operator +,-,*
+
2+3=5
-
7/29/2019 Dot Net Along With C#
61/181
While Statements
WHILE statements
A WHILE loop will check a condition and then continues toexecute a block of code as long as the condition is true.
Syntax:
while( condition )
{
statement;}
-
7/29/2019 Dot Net Along With C#
62/181
WHILEStatement
UsingSystem;
Class whilestate
{
static void Main()
{
int i=0;while (i
-
7/29/2019 Dot Net Along With C#
63/181
Do While Statements
DO WHILE statements In WHILE loop statements, if condition is false then the
statement will not execute.
But in DO WHILE statement, first the statement in the blockof code executes at least once then checks the condition.
Syntax:
do
{
statement;
}while( condition );
DO WHILE Statements
-
7/29/2019 Dot Net Along With C#
64/181
DO WHILE Statements
Class dowhilestate
{static void Main()
{
int i=0;
do{
System.Console.Write({0} ,i);
i++;
} while (i
-
7/29/2019 Dot Net Along With C#
65/181
For Statement
FOR statements The for loop works like a while loop, except that the syntax of for
loop includes initialization and condition.
The forloop syntax explains clearly.
The contents in the syntax is separated by semicolons.
Syntax:
For( initialization; condition; iterator )
{statement;
}
-
7/29/2019 Dot Net Along With C#
66/181
For Statements
Class forstate
{static void Main()
{
int i=0;
for(int k=0;k
-
7/29/2019 Dot Net Along With C#
67/181
Foreach Statement
FOREACH statements
This is similar to for statement.
The foreach loop is used to iterate through items in the list.
This is used for arrays or collection such as arraylist.
Syntax:
foreach( datatype varname in arrayname)
{
statement;
}
-
7/29/2019 Dot Net Along With C#
68/181
Foreach Statement
Using System;
Class foreachstate
{
static void Main()
{
int[] number={0,1,2,3,4,5,6,7,8,9};foreach(int line in number){
Console.Write({0} ,line);
}
}}
0 1 2 3 4 5 6 7 8 9
OUTPUT:
-
7/29/2019 Dot Net Along With C#
69/181
-
7/29/2019 Dot Net Along With C#
70/181
Introduction
Static Constructor
Overloaded Constructor
Copy Constructor
Contents:
CONSTRUCTOR
-
7/29/2019 Dot Net Along With C#
71/181
CONSTRUCTOR
Constructor is a specialmethod, evokedautomatically wheneverobject is created.
The class and the methodboth has same name.
It has no return type.
The are four types ofconstructors:
1. StaticConstructor2. OverloadedConstructor
3. Copyconstructor
4. DefaultConstructor
Syntax:
class Myclass
{
public Myclass
{
}
}
Object of the class can becreated by using the newkeyword.
E.g: Myclass m=new Myclass
Constructors can be declared"private or protected butcommonly public is used.
-
7/29/2019 Dot Net Along With C#
72/181
Simple Constructor
class Cons
{int length, height;
public Cons ( int a, int b)
{
length=a;
height=b;
}
publicint area ()
{return a*b;
}
}
class Class1
{
publicvoid Main()
{Cons c=new Cons ( 3,4);
int n=c.area();
Console.WriteLine( The area is = +n);
}
}
OUTPUT
The area
is = 12
Static Constructor
-
7/29/2019 Dot Net Along With C#
73/181
Static Constructor
Gets called before the first
object is created of theclass
Syntax:
class Sample
{
static Sample //staticconstructor
{
}
}
It is used to perform an
action only once.
Keyword static is used.
It does not contain any
access modifier,noparameters.
There can be only one static
constructor in the class.
OUTPUT:
-
7/29/2019 Dot Net Along With C#
74/181
class State
{
static State()
{
Console. WriteLine (This is one);
}
public void static land()
{
Console. WriteLine (This is two);
}
}
class Sample
{
static void Main()
{
State. land();
State. land();
}
}
*This is one
This is two
*This is two
Overloaded Constructor
-
7/29/2019 Dot Net Along With C#
75/181
Overloaded Constructor
Eg:class Load
{
public Load()
{
Console. WriteLine (No Arguments inthis method);
}public Load( int i )
{
Console. WriteLine (The number is{0}, I );
}
public Load( int i, int j)
{Console. WriteLine ({0}+{1}={2}, i ,j
,+(i+j));
}
}
class Sample{
static void Main()
{
Load o=new Load();
Load o1=new Load(6);
Load o2=new Load(2,3);}
}
OUTPUT:
No Arguments in this methodThe number is 6
2+3=5
constructors with different set of parameters
Copy Constructor
-
7/29/2019 Dot Net Along With C#
76/181
Copy Constructor
Eg:
class Person
{
private int age;
private string name;
public Person (Person p) //copy constructor
{
age =p. age;name=p. name;
}
public Person (int age, string name) //instance
{//constructor
this. age= age;
this. name= name;
}
public string Details //get details{
get
{
returnname + is +age.Tostring();
}}
}
Class Sample
{
static void Main()
{
Person h=new
Person(23,Ram);Person h1=new Person (h);
Console. WriteLine(h. Details);
Console. WriteLine(h1. Details);
}
}
OUTPUT:
Ram is 23
Ram is 23
A copy constructor is a special constructor used to create a new object
as a copy of an existing object.
-
7/29/2019 Dot Net Along With C#
77/181
Destructor
In simple terms a destructor is a member that
implements the actions required to destruct an
instance of a class.
Opposite to a constructor.
Syntax:
~ classname()
{
statement;
}
-
7/29/2019 Dot Net Along With C#
78/181
-
7/29/2019 Dot Net Along With C#
79/181
Introduction
Simple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Using Keywords
Contents:
-
7/29/2019 Dot Net Along With C#
80/181
Inheritance
Access Modifier public---visible to every code
private---visible only inside that class
protected--- visible only to its class and derived type
internal----visible inside the assembly
protected internal---within the assembly and its derived type.
Syntax:
Class derivedClass:baseClass (deriving from base class)
{
} If a function or a property in the base class is declared as virtual it
can be overridden in any derived classes
The new keyword should be used when we intend to hide a method.
Types of Inheritance
-
7/29/2019 Dot Net Along With C#
81/181
Types of Inheritance
The mechanism of designing or constructing one class from anotheris called inheritance.
One class acquiring property of another class. There are four types of inheritance
1. Single Inheritance
2. Hierarchical Inheritance
3. Multiple Inheritance
4. Multilevel Inheritance
A
B
B
A
BB
A
C
BA
C
Single
Hierarchical
Multilevel
Multiple
C# does not support Multiple Inheritance.
Simple Inheritance
-
7/29/2019 Dot Net Along With C#
82/181
Simple Inheritance
class Animal
{public void name()
{
Console.WriteLine("This isAnimals World");
}
public void type(){
Console.WriteLine("Thereare many types");
}
public void size()
{ Console.WriteLine("Thereare are big animals");
}
}
class Cat : Animal
{
public void kitty(){
Console.WriteLine(" THis is aCat");
}
}
class Simpleinherit
{
static void Main()
{
Cat c = new Cat();
c.kitty();
c.name();
c.size();c.type();
}
}
This is a Cat.
This is animals World.
There are big animals.
There are many types
Multilevel
-
7/29/2019 Dot Net Along With C#
83/181
Multilevel
class Base
{
public virtual void who()
{
Console.WriteLine("This is who fromBase Class");
}
}
class Derived : Base
{ public override void who()
{
Console.WriteLine("This is who fromDerived Class");
}
}
class Derived1 : Derived
{}
class Derived2 : Derived1
{
}
class Multilevel
{static void Main()
{
Derived2 d2 = newDerived2();
Base b1 = new Base();
b1.who();}
}
This is Who from Derived
Class
Hi hi l
-
7/29/2019 Dot Net Along With C#
84/181
Hierarchical
public class Shape
{
public double area;public Shape()
{
area=0.0;
}
public void display( string name, doublea)
{ Console. WriteLine(The area of +name + is +a);
}
}
public class Square: Shape
{
int side;
public Square( int s){
side=s;
}
public void calculatearea1()
{
area= 4*s*s;
}
}
public class Circle: Shape
{
int radius;public Circle (int r)
{
radius=r;
}
public void calculatearea2()
{
area=3.14*r*r;}
}
class Sample
{
static void Main()
{
Square s=new Square(5);
s.calculatearea1();s. display (square,s.area);
Circle c=new Circle(5);
c.calculatearea2();
c. display(circle,c.area);
}
}
The area of square is 100
The area of circle is 78.5
OUTPUT:
Using Keywords
-
7/29/2019 Dot Net Along With C#
85/181
Using Keywords
class Animal
{
public Animal()
{
Console.WriteLine("Animalconstructor");
}
public void Greet()
{
Console.WriteLine("Animal saysHello");
}
public void Talk()
{
Console.WriteLine("Animal talk");
}
public virtual void Sing(){
Console.WriteLine("Animal song");
}
}
class Dog : Animal
{
public Dog(){
Console.WriteLine("Dog constructor");
}
public new void Talk() //Hiding Methods usingnew keyword
{
Console.WriteLine("Dog talk");
}public override void Sing()
{
Console.WriteLine("Dog song");
}
}
Class Mainclass
{
static void Main(){
Dog d1 = new Dog();
d1.Talk();
d1.Sing();
d1.Greet();
}
}
Animal constructorDog constructor
Dog talk
Dog song
Animal says Hello
OUTPUT:
-
7/29/2019 Dot Net Along With C#
86/181
-
7/29/2019 Dot Net Along With C#
87/181
Introduction
Abstract Method Non-Abstract Method
Partial-Implementation
Using Interface
Contents:
-
7/29/2019 Dot Net Along With C#
88/181
Abstract Class
An abstract class is a type of class that allows inheritancebut can never be instantiated.
An abstract class contains abstract and non-abstract
methods. They contain one or more abstract method that do
not have implementation. Abstract methoddo not have
method body, they are implicitly virtual. Non-Abstractmethodcontain method body.
They provide only Partial Implementation. This is done by
declaring the derived class as abstract class, we can avoid
implementing of all or certain abstract methods.
An abstract class can also implement from interface. In thismethod body should be provided while implementing from
interface.
b h d
-
7/29/2019 Dot Net Along With C#
89/181
Abstract Method
class Baseclass{
public void basemethod()
{
Console.WriteLine(This is Basemethod);
}
}abstract class Abclass:Baseclass
{
public void absmethod();
}
class Subclass:Absclass
{
public override void absmethod(){
Console.WriteLine(This is Absmethod);
}
}
class Mainclass{
static void Main()
{
Subclass s=new Subclass();
s.basemethod();
s.absmethod();}
}
OUTPUT:
This is Base methodThis is Abs method.
N Ab M h d
-
7/29/2019 Dot Net Along With C#
90/181
Non-Abstract Method
abstract class nonabs{
public void nonabsmethod()
{
Console.WriteLine(This is non abstract
method);
}
}
class Subclass:nonabs
{
}
class Mainclass
{
static void Main()
{
Subclass s=new Subclass();
s.nonabsmethod();
}
}
OUTPUT:
This is non abstract method
U i I t f
-
7/29/2019 Dot Net Along With C#
91/181
Using Interface
interface Interclass{
void intermethod()
}
abstract class Abclass:Interclass
{
public void intermethod()
{Console.WriteLine(This is Intermethod);
}
public abstract void absmethod();
}
class subclass:Absmethod
{public abstract void absmethod()
{
Console.WriteLine(This is Absmethod);
}
}
class Mainclass{
static void Main()
{
Subclass s=new Subclass();
s.absmethod();
s.intermethod();}
}
OUTPUT:
This is Inter method.This is Abs method.
P ti l I l t ti
-
7/29/2019 Dot Net Along With C#
92/181
Partial Implementation
abstract class Baseclass{
public abstract void absmethod1();
public abstract void absmethod2();
}
abstract class Subabs:Baseclass
{
public override void absmethod1()
{Console.WriteLine(This is Baseabsmethod 1);
}
}
class Subclass:Subabs
{
public override void absmethod2()
{
Console.WriteLine(This is Subabsabmethod 2);
}
}
class Mainclass{
static void Main()
{
Subclass s=new Subclass()
s.absmethod2();
s.absmethod1();
}}
OUTPUT:
This is Sub absmethod 2.
This is Base absmethod 1.
-
7/29/2019 Dot Net Along With C#
93/181
-
7/29/2019 Dot Net Along With C#
94/181
DELEGATES
-
7/29/2019 Dot Net Along With C#
95/181
DELEGATES
Delegate is type which holds the method(s) reference in an
object. It is also referred as a type safe function pointers. Declaration:
public delegate type_of_delegate delegate_name()
Example :publicdelegate int mydelegate(int delvar1,int
delvar2)
if you are referring the method with two int parameters and
int return type the delegate which you are declaring should
be the same format. This is how it is referred as type safe
function pointer .
If the delegate contains a return type ofvoid, then it is
automatically aliased to the type of
System.MulticastDelegate.
-
7/29/2019 Dot Net Along With C#
96/181
If the delegate contains a non-void return type then it is
aliased to System.Delegate class and it cannot support
multiple methods.
In C#, delegates act as an intermediary between an event
source and an event destination.Eg: A group of people representing a company.
What if you want to call three methods when a button is
clicked?.At this point of time we use multi-cast Delegate .
Single Cast
-
7/29/2019 Dot Net Along With C#
97/181
public delegate double TestDelegate(int a,int b);
class Class1
{
static double Method1(int val1,int val2){return val1*val2;
}
static void Main(){
//Creating the Delegate Instance
TestDelegate delObj = new TestDelegate(Method1);
Console.Write("Please Enter Values");
int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());
//use a delegate for processing
double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res)
}
}
Please Enter Values
3
6
Result:18
OUTPUT:
Multi Cast
-
7/29/2019 Dot Net Along With C#
98/181
Multi-Cast
delegate void Multicast();
class Simplemulticast{
static public void Method1()
{
Console.WriteLine("Your inMethod1");
}
static public void Method2()
{Console.WriteLine("Your in
Method2");
}
static void Main()
{
Multicast m = newMulticast(Method1);
Multicast m1 = newMulticast(Method2);
m();
m1();
Multicast m2 = m + m1;
m2();
}
}
OUTPUT:
Your in Method1Your in Method2Your in Method 1
Your in Method2
-
7/29/2019 Dot Net Along With C#
99/181
Events
-
7/29/2019 Dot Net Along With C#
100/181
Events are the actions of the system on user
manipulations(e.g. mouse clicks, key press, timer etc.) or any
event triggered by the program.
A large goal of design delegates is their applicability in events
model of .Net.
communication between event source and event receiver is
called delegate.
event source=objects that raise events.
event receiver=object that responds to events.
Ex: Speaking with a friend on phone.
event source=you; event receiver=your friend;telephone=delegate;
-
7/29/2019 Dot Net Along With C#
101/181
//Delegate Declaration()
public delegate void newdelegate();
//Event Declaration ()
public event newdelegate newevent;
Event method consists of procedure name followed by two
arguments.
The first argument is object firing and second is of
System.EventArgs receiver. The += is used to hook up the event as a delegate i.e a
method stand for another method.
class Myclass
{
public delegate void MyDelegate(string
-
7/29/2019 Dot Net Along With C#
102/181
p g y g ( gmessage);
public event MyDelegate Myevent;
public void RaiseEvent(string message)
{
if (Myevent != null)Myevent(message);
}
}
class Event1
{
static void Main()
{
Myclass c1 = new Myclass();
c1.Myevent += newMyclass.MyDelegate(c1_Myevent);
Console.WriteLine("Please enter yourmsg here");
string msg = Console.ReadLine();
c1.RaiseEvent(msg);
}
static void c1_Myevent(string message)
{
Console.WriteLine("your message is{0}", message);
}
}
OUTPUT:
Please enter your msg here
Welcome to LST
Your message is Welcome to LST
-
7/29/2019 Dot Net Along With C#
103/181
-
7/29/2019 Dot Net Along With C#
104/181
Interface
-
7/29/2019 Dot Net Along With C#
105/181
Interface
C# does not support multiple inheritance. So, c# provides analternative approach known as interface.
An interface is a reference type object with no
implementation.
So the interface doesn't actuallydoanything but only has a
signature for interaction with other classes or interfaces. It contains only definition, does not contain methods or
properties code inside an interface.
Syntax:
privateClass derivedClass:baseClass , InterfaceX , InterfaceY
(deriving from interface)
{
}
Simple Interface
-
7/29/2019 Dot Net Along With C#
106/181
p
interface In1 //Interface1
{
void show();}
interface In2 //Interface2
{
void Display();
}
class Interface1:In1,In2 //Simpleinheritance
{
public void show(){
Console.WriteLine("This is In1 Showmethod");
}
public void Display()
{
Console.WriteLine("This is In2 Displaymethod");
}static void Main()
{
Interface1 i = new Interface1();
i.Display();
i.show();
}
}
This is In1 Show method.
This is In2 Display method.
OUTPUT:
Explicit Interface
-
7/29/2019 Dot Net Along With C#
107/181
interface Int1 //Explicit interface Implementation
{ //Implementation of 2 methods of samename
void show();
}
interface Int2
{
void show();
}
class Interface2:Int1,Int2
{
void Int1.show()
{
Console.WriteLine("This is Show from Int1");}
void Int2.show()
{
Console.WriteLine("This is Show from Int2");
}
static void Main()
{
Interface2 l = new Interface2();
Int1 i1 = (Int1)l; //casting
i1.show();
Int2 i2 = (Int2)l;
i2.show(); //casting
}
}
This is Show from Int1.This is Show from Int2
OUTPUT:
Multiple Interface
-
7/29/2019 Dot Net Along With C#
108/181
interface Addition
{
int add();
}interface Multiplication
{
int mul();
}
class Compare : Addition, Multiplication
{
int x, y;
public Compare(int x, int y){
this.x = x; //Current value of X
this.y = y; //Current value of y
}
public int add()
{
return x + y;}
public int mul()
{
return x * y;
}
}
class Mulinterface
{
static void Main()
{
Compare c = new Compare(5, 5);
Addition a = (Addition)c;//casting
Console.WriteLine(a.add());//create an instance ofimplementing class//and then cast the object to theinterface
Multiplication m = (Multiplication)c;//casting
Console.WriteLine(m.mul());
}}
OUTPUT:
1025
-
7/29/2019 Dot Net Along With C#
109/181
-
7/29/2019 Dot Net Along With C#
110/181
-
7/29/2019 Dot Net Along With C#
111/181
Introduction
Simple Structs
Using Method
Using Interface
Using Constructors
Contents:
Structure
-
7/29/2019 Dot Net Along With C#
112/181
Structure
A C# structure is a value type The keyword structcan be used to declare a structure.
Structure Declaration
Syntax:
struct
{//Structure members
}
Remember that unlike classes, the strcut object can also be
created without using the new operator.
Like: MyStruct ms;
By default its private and therefore cannot be accessed
outside the struct definition
-
7/29/2019 Dot Net Along With C#
113/181
outside the struct definition.
But static methods can access only other static members andthey can't invoke by using an object of the structure. They
can invoke only by using the struct name.
Struct is not permitted to declare Structs, does not support
default constructors.
Since structs doesn't support inheritance, we can't use the
keywords virtual, override, new, abstract etc with a struct
methods. C# struct types are never abstract and are always
implicitly sealed. The abstract or sealed modifiers are notpermitted in a struct declaration
Simple & With Method
-
7/29/2019 Dot Net Along With C#
114/181
using System;struct MyStruct{public int x;public int y;}class MyClient{public static void Main(){MyStruct ms ;ms.x = 10;ms.y = 20;int sum = ms.x + ms.y;Console.WriteLine("The sum is
{0}",sum);}}
OUTPUT
using System;struct MyStruct
{static int x = 25;static int y = 50;public void SetXY(int i, int j){x = i;y = j;}public static void ShowSum()
{int sum = x + y;Console.WriteLine("The sum is{0}",sum);}}class MyClient{public static void Main(){MyStruct ms = new MyStruct();ms.SetXY(100,200);MyStruct.ShowSum();}}OUTPUTThe sum is 30.
The
sum is
300.
Interface & Constructor
-
7/29/2019 Dot Net Along With C#
115/181
using System;interface IInterface
{void Method();}struct Complex : IInterface{public void Method(){
Console.WriteLine("StructMethod");}}class MyClient{public static void Main()
{Complex c1 = new Complex();c1.Method();}}
using System;struct MyStruct
{int x ;int y ;public MyStruct(int i, intj):this(i+j){ }public MyStruct(int i)
{ x = y = i; }public void ShowXY(){Console.WriteLine("The fieldvalues are {0} & {1}",x,y); }}class MyClient{
static void Main(){MyStruct ms1 = newMyStruct(10,20);ms1.ShowXY();}} Output:
Struct Method
The field value
Are 30&30.
Output:
-
7/29/2019 Dot Net Along With C#
116/181
-
7/29/2019 Dot Net Along With C#
117/181
Introduction
ArrayList
HashTable
Stack
Queue
Contents:
Collections
-
7/29/2019 Dot Net Along With C#
118/181
A collection in C# is a group of related objects held in astructure
The .NET Foundation Class Library contains a namespace
called System.Collections that provides classes to manage
data structures like arrays, lists and maps.
The ArrayList class is similar to the Array class except that
its size can grow dynamically.
The Queue and Stack classes provide the First In First Out
and Last In First Out types of collections respectively.
ArrayList
-
7/29/2019 Dot Net Along With C#
119/181
Array is used to store onlyobjects of same type, where
as in arraylist we can storedifferent types of objectswhich is stored as objecttype only.
It uses its index to refer toan object in its collection.
The Capacity property getsor sets the number of itemsthat the ArrayList objectcan contain.
You can Add an item by
using Add() and remove anitem using Remove()method.
using System;
using System.Collections;
class Collections1
{static void Main()
{
int i = 10;
string g = "abc";
ArrayList a =new ArrayList();
a.Add("alexy");
a.Add(i);
a.Add(g);
for (int x = 0; x < a.Count; x++)
Console.WriteLine(a[x]);
}
}
Alexy
10
abc
HashTable
-
7/29/2019 Dot Net Along With C#
120/181
The Hashtable provides a faster way of storage and
retrieval of items of the object type.
The Hashtable class provides support for key basedsearching.
These keys are unique hash codes that are unique to aspecific type.
To remove an item from the Hashtable class, theRemove() method is used.
The statement hashTable.Remove(3) would remove theitem Jini from the Hashtable object created in the code.
using System;
using S stem Collections; O t t
-
7/29/2019 Dot Net Along With C#
121/181
using System.Collections;
class Test
{
static void Main(){
Hashtable hashTable = new Hashtable();
hashTable.Add(1, "Joydip");
hashTable.Add(2, "Manashi");
hashTable.Add(3, "Jini");
hashTable.Add(4, "Piku");
Console.WriteLine("The keysare:--");foreach (int k in hashTable.Keys)
{
Console.WriteLine(k);
}
Console.WriteLine("Please enter the keyto search");int p = int.Parse(Console.ReadLine());
Console.WriteLine(hashTable[p].ToString());
}
}
The keysare:--
4
3
2
1Please enter the keyto search
2
Manashi
Output:
Queue
using System;
-
7/29/2019 Dot Net Along With C#
122/181
The Queue is a datastructure that provides aFirst-in-First-out collectionof items of theSystem.Object type.
The newly added items arestored at the end or the rearof the Queue and items aredeleted from the front of theQueue.
The Enqueue() method isresponsible for storingitems at the rear of theQueue and
the method Dequeue()removes them one at a timefrom the front.
using System.Collections;
classTest
{
static void Main()
{
Queue queueObject = newQueue();
queueObject.Enqueue("Joydip"
);queueObject.Enqueue("Steve");
queueObject.Enqueue("Jini");
while (queueObject.Count > 0)
Console.WriteLine(queueObject
.Dequeue());
}
} Joydip
Steve
Jini
Stack
-
7/29/2019 Dot Net Along With C#
123/181
The Stack class is one thatprovides a Last-in-First-out (LIFO) collection ofitems of the System.Objecttype.
The last added item isalways at the top of theStack and is also the first
one to be removed. The Push() method is
responsible for storingitems in the Stack
The method Pop() removesthem one at a time from the
top of the Stack.
using System;
using System.Collections;
class Test
{
static void Main()
{
Stack stackObject = newStack();
stackObject.Push("Joydip");
stackObject.Push("Steve");
stackObject.Push("Jini");
while (stackObject.Count > 0)
Console.WriteLine(stackObject.Pop());
}
}
Jini
Steve
Joydip
-
7/29/2019 Dot Net Along With C#
124/181
-
7/29/2019 Dot Net Along With C#
125/181
Introduction
Single-Dimensional Array
Multi-Dimensional Array
Jagged Array
Array Class Properties
Contents:
Arrays
-
7/29/2019 Dot Net Along With C#
126/181
Its Group of related data items that share a common name.
In C#, arrays can be declared as fixed length or dynamic.
Fixed length array can stores a predefined number of items,
while size of dynamic arrays increases as you add new items
to the array. You can declare an array of fixed length or
dynamic.
int [] intArray; Eg: Dynamic Array
int [] intArray; Eg: fixed Array creates memory
location for 5 intarray,
intArray = new int[5]; beginning from 0,1,2,3,4 System.Array class is the name space, used as an abstract
base type.
-
7/29/2019 Dot Net Along With C#
127/181
The variables in an array is called elements
The value of each individual element in an array is accessed
through its index value.
Arrays in C# are zero-based; i.e. the first element in an array will
always have an index of zero.
Arrays can be divided into four categories. These categories are1. single-dimensional arrays,
2. multidimensional arrays or rectangular arrays,
3. jagged arrays, and
4. mixed arrays
-
7/29/2019 Dot Net Along With C#
128/181
Single Array
-
7/29/2019 Dot Net Along With C#
129/181
class simplearray{
static void Main()
{
int[] intarray = newint[4];
intarray[0] = 1;
intarray[1] = 2;intarray[2] = 3;
intarray[3] = 4;
foreach (int i in intarray)
{
Console.WriteLine(i.ToString());}
}
}
OUTPUT:
1
23
4
Multi dimensional
-
7/29/2019 Dot Net Along With C#
130/181
These are array with more than one dimensional.It isdeclared as follows
string[ , ] name; //2D Array
string[ , , ]name; //3D Array
After declaring we can initialize the array.
int[,] num=new int[3,2]{{5,6},{2,7},{0,1}};
Here it can store 6 items of int and an examp le of fixed array
string[,] name=new string[,]{ {alexy,dede},{roja,raja}};
here it stores 4 items of sting and an example of dynamic
array.
Multi Array
-
7/29/2019 Dot Net Along With C#
131/181
class multiarray
{
static void Main()
{
string[,] namearray = newstring[,]
{
{"Rosy","Amy"},
{"Peter","Albert"},{"Raja","Alexy"}
};
for (int i = 0; i < 3; i++)
for (int j = 0; j < 2; j++)
Console.WriteLine("Element[{0},{1}]={2}", i, j, namearray[i, j]);
Console.Read();
}
}
OUTPUT:
Element[0,0]=Rosy
Element[0,1]=Amy
Element[1,0]=Peter
Element[1,1]=AlbertElement[2,0]=Raja
Element[2,1]=Alexy
Two Dimensional Array
-
7/29/2019 Dot Net Along With C#
132/181
class Twodimentional
{
public static void Main(){
int[,] x;
x = new int[4, 4];
x[0, 0] = 1;
x[1, 1] = 1;x[2, 2] = 1;
x[3, 3] =1;
Console.WriteLine(x[0, 0] + " " + x[0, 1] + " " + x[0, 2] + " " + x[0, 3]);
Console.WriteLine(x[1, 0] + " " + x[1, 1] + " " + x[1, 2] + " " + x[1, 3]);
Console.WriteLine(x[2, 0] + " " + x[2, 1] + " " + x[2, 2] + " " + x[2, 3]);Console.WriteLine(x[3, 0] + " " + x[3, 1] + " " + x[3, 2] + " " + x[3, 3]);
}
}
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
OUTPUT:
Jagged Arrays
-
7/29/2019 Dot Net Along With C#
133/181
Jagged Arrays
Jagged Array is simply called array of arrays.
In this elements of array are arrays.
The elements of jagged array can be of different dimensionsand sizes.
Example:
int[][] jarray=new int [3][];
The example declares an single-dimensional array that has
three elements, each of which is a single-dimensional array of
-
7/29/2019 Dot Net Along With C#
134/181
integers:
int[][] jarray=new int [3][];
These elements must be initialized before using in the
program.
jarray[0]=new int[]{1,2,3,4,5};
jarray[1]=new int[]{22,66};
jarray[3]=new int[]{9,5,33,66,1,10,38,44};
We can access individual array elements like in the followingway:
int[][] jarray1=
-
7/29/2019 Dot Net Along With C#
135/181
{
new int[]{ 1,2,3,4,5},
new int[]{5,6,7,8},
new int[]{22,99}
};
jarray1[0][1]=77;
//assigning 77 to second element [1] of first array [0];
jarray1[2][1]=66;
//assigning 66 to second element [1] of third array[2];
The following is a jagged array three elements of two-dimensional
int[][,] jaggedArray4 = new int[3][,]
{
new int[,] { {1,3}, {5,7} },
new int[,] { {0,2}, {4,6}, {8,10} },
new int[,] { {11,22}, {99,88}, {0,9} }
};
Jagged Array
-
7/29/2019 Dot Net Along With C#
136/181
class Jagged
{
int[][] x = newint[2][];
void set()
{
x[0] = newint[2];
x[1] = new int[2];
x[0][0] = 1; //first array,first
elementx[0][1] = 2; //first array,second
element
}
void show()
{
for (int i = 0; i < 2; i++)
{for (int j = 0; j < 2; j++)
{
Console.WriteLine(x[i][j]);
}
}
}
public static void Main()
{
Jagged j = new Jagged();
j.set();
j.show();
}
}
OUTPUT:
1
2
00
ARRAY CLASS PROPERTIES.
-
7/29/2019 Dot Net Along With C#
137/181
IsFixedSize : Return a value indicating if an Array has a fixed size or not.
IsReadOnly : Returns a value indicating if an Array is read- only or not. Length : Returns the total number of items in all hedimensions of
an Array .
Rank : Returns the number of dimensions of an Array. BinarySearch:This method searches a one-dimensional sorted Array for a
value, using a binary search algorithm.
Clear : This method removes all items of an Array and sets a
range of items in the array to 0. Clone : This method creates a shallow copy of the Array.
Copy : This method copies a section of one Array to another Array
and performs type casting and boxing as required.
CopyTo : This method copies all the elements of the current one-
dimensional Array to the specified one-dimensional Array
starting at the specified destination CreateInstance : This method initializes a new instance of the Array class.
GetEnumerator : This method returns an IEnumerator for the Array.
GetLength : This method returns the number of items in an Array.
ARRAY CLASS PROPERTIES.
-
7/29/2019 Dot Net Along With C#
138/181
GetLowerBound : This method returns the lower bound of an Array.
GetUpperBound : This method returns the upper bound of an Array. GetValue : This method returns the value of the specified item in an
Array.
IndexOf : This method returns the index of the first occurrence of a
value in a one-dimensional Array or in a portion of it. Initialize : This method initializes every item of the value-type Array
by calling the default constructor of the value type.
LastIndexOf : This method returns the index of the last occurrence of a
value in a one-dimensional Array or in a portion of it.
Reverse : This method reverses the order of items in a one-
dimensional Array or in a portion of the Array.
SetValue : This method sets the specified items in the current Array to
the specified value.
Sort : This method sorts the items in one-dimensional Arrayobjects.
Using array properties
-
7/29/2019 Dot Net Along With C#
139/181
using System;Class Program
{
static void Main()
{
int[]num={99,24,56,3,15};
Array.Sort(num);
foreach(int I in num)
Console.WriteLine(I);
Console.WriteLine(Length=+num.length);
}
}
Output
3
15
2456
99
Length=5
-
7/29/2019 Dot Net Along With C#
140/181
Enumerator
-
7/29/2019 Dot Net Along With C#
141/181
a distinct type consisting of a set of named constants called the
enumerator.
Syntax:
enum Eg:enum Months
{ {
// Enumeration list jan,feb,mar,apr
} }
By default the first enumerator has the value of zero and the value
of each successive enumerator is increased by 1.
The following are the restrictions apply to an enum type in C#
They can't define their own methods.
They can't implement interfaces. They can't define properties or indexers.
the use of enum makes the code more readable and self-
documenting.
Simple Enum
-
7/29/2019 Dot Net Along With C#
142/181
using System;enum Months : long{jan = 10,feb = 20,mar}class MyClient{
public static void Main(){long x = (long)Months.jan;long y = (long)Months.feb;long z = (long)Months.mar;Console.WriteLine("JANUARY={0},FEbriary ={1},March={2}",x,y,z);}}
OUTPUT:
JANUARY=10,FEBUARY=20,
MARCH=21
-
7/29/2019 Dot Net Along With C#
143/181
-
7/29/2019 Dot Net Along With C#
144/181
Introduction
Try and Catch Block Multiple Catch Block
Finally Block
User Exception
Contents:
Exception Handling
-
7/29/2019 Dot Net Along With C#
145/181
To detect and handle run time errors.
These exception can be due to user, logic or system errors.
Three keywords are mainly used in this i.e.
try, catch and finally.
The try encloses the statements that might throw an
exception whereas catch handles an exceptions if one exits.
The finally can be used for doing any clean up process.
Syntax:
try catch( type e) finally
{ { {
} } }
In try if there is no exception, it transfers to finally
block. The Finally block is always executed.
-
7/29/2019 Dot Net Along With C#
146/181
y y
There is no usage of break, continue, return, goto.
C# provides standard exception or user can create
exception provided that it should inherit from
System.Exception class.
Run-time error: after successful compilation
program may produce wrong results.
Compile time error: syntax errors will be detected
and displayed by compiler.
Normal coding: Output:
-
7/29/2019 Dot Net Along With C#
147/181
class Notry
{static void Main()
{
int e = 0;
int div = 100 / e;
Console.WriteLine(div);
}
}
This code Will raise an
Exception thatDivideByZeroException isUnhandled.
Now the code next to itcontains TRY and CATCHblock.
Here in this controls passesfromTRY block to CATCHblock. Then it will executethis CATCH block andcontinues with theprogram.
Using try and catch
-
7/29/2019 Dot Net Along With C#
148/181
class Singletry
{
public static void Main(){
int i = 0;
int div=0;
try
{
div = 100 / i;
Console.WriteLine("This lineis Exception");
}
catch (DivideByZeroExceptione)
{
Console.WriteLine("ExceptionOccured");
}
Console.WriteLine("Result is{0}", div);
}
}
Output:
This line is Exception
Exception OccurredResult is 0
Multiple Catch Block
class Multicatch
{ OUTPUT:
-
7/29/2019 Dot Net Along With C#
149/181
{
static void Main()
{
int[] a ={ 5, 10 };int b = 5;
try
{
int x = a[2] / b - a[1];
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(e);
}catch (ArgumentNullException o)
{
Console.WriteLine(o);
}
catch (ArrayTypeMismatchException n)
{
Console.WriteLine(n);
}
catch (DllNotFoundException k){
Console.WriteLine(k);
}
int y = a[1] / a[0];
Console.WriteLine(y=y);
}
}
OUTPUT:
System.IndexOutOfRangeException:
Index was outside the bounds of thearray.
at
ConsoleApplication1.ErrorHandling.Multi
catch.Main() in C:\Documents and Se
ttings\Administrator\Desktop\Alexy\Proj
ects\ConsoleApplication1\ConsoleApplic
ation1\ErrorHandling\Multicatch.cs:line 15
Y=2
Array element 2 does not exist,
hence index 2 is out of range, so
the try block raises an exceptionand catching the right
exception, leaving the rest
alone.
Finally Block
class Finallyblock
{ OUTPUT
-
7/29/2019 Dot Net Along With C#
150/181
{
static void Main()
{
int i = 0;
int div = 0;
try
{
div = 100 / i;
Console.WriteLine("This line is
Exception");}
catch (Exception e)
{
Console.WriteLine("INVALID");
}
finally{
Console.WriteLine("finally");
Console.WriteLine("Result is {0}", div);
}
}
}
OUTPUT:
THIS IS INVALID DIVISION
finally block
Result is 0
First the try block will raise
an exception, to the catch
block. But note that the
program is not terminated anit continues. How ever the
finally block will be executed.
User Exception
-
7/29/2019 Dot Net Along With C#
151/181
class Myexception : Exception
{
public Myexception(stringMesssage):base(Messsage)
{
Console.WriteLine("user definedexception");
}
}
class OwnException
{public static void Main()
{
try
{
throw newMyexception(Raja");
}
catch (Myexception e)
{Console.WriteLine(e.Message);
}
Console.WriteLine("LastStatement");
}
}
OUTPUT:
user defined exception
AlexyLast Statement
-
7/29/2019 Dot Net Along With C#
152/181
Sealed Class
-
7/29/2019 Dot Net Along With C#
153/181
Sealed Classes is used to restrict the feature of inheritance.
A class is declared as sealed simply by using the keyword
sealed.
In C# structs are implicitly sealed.
Syntax:
Sealed class SealedClass
{....
}
Example
class Class1 OUTPUT
-
7/29/2019 Dot Net Along With C#
154/181
class Class1
{
static void Main(string[] args){
SealClass Cls = new SealClass();
int total = Cls.Add(4, 5);
Console.WriteLine("Total = " +total.ToString());
}
}
sealed class SealClass
{
public int Add(int x, int y)
{return x + y;
}
}
OUTPUT:
Total=9
Sealing Methods
-
7/29/2019 Dot Net Along With C#
155/181
In C# a method can not be declared as sealed.
However when we override a method in a derived class, wecan declare the overridden method as sealed.
By declaring it as sealed, we can avoid further overriding of
this method.
Sealed keyword serves the purpose of sealed. If a class is
derived from a sealed class,compiler throws an error.
We can mark a class or method as sealed for commercial
reasons, in order to prevent a third party from extending our
classes.
-
7/29/2019 Dot Net Along With C#
156/181
-
7/29/2019 Dot Net Along With C#
157/181
Introduction
Namespace and Instance
Writing in a file
Reading from a file
Contents:
Files
-
7/29/2019 Dot Net Along With C#
158/181
With any programming language there is always a need toread and write to files.
The class FileStream, which is actually derived from the
Stream class, adds to Stream the functionality needed to read
and write to files.
Like other languages, C# utilizes a Stream class, which gives
basic functionality when working with streams (any situation
where you need to read and write data to some endpoint). The
class FileStream, which is actually derived from the Streamclass, adds to Stream the functionaly needed
to read and write to files.
Namespace and Instance
-
7/29/2019 Dot Net Along With C#
159/181
System.IO provides all the necessary classes, methods, and properties for
manipulating directories and files. create an instance of FileStream:
FileStream file = newFileStream(C://path.txt", FileMode.option,
FileAccess.option);
FileMode specifies what the FileStream should do with the file to begin with.The options are: Append, Create, CreateNew, Open, OpenOrCreate, or
Truncate, and can be accessed by FileMode.option.
FileAccessspecifies the file priveledges. The options are: Read, ReadWrite, or
Write, and can be accesed by FileAccess.option.
After reading or writing close the file
file.Close();
Writing to a file
-
7/29/2019 Dot Net Along With C#
160/181
To write to a file we will need to use class StreamWriter,which is derived from the TextWriter class.
StreamWriter sw = new StreamWriter(file);
With StreamWriter, you have two options for writing to a file:Write, or WriteLine.
sw.Write("Hello file system world!");
Now don't forget to close the stream when you are done!
sw.Close();
using System;
using System.IO;
class Fileclass
{
Output:
S
-
7/29/2019 Dot Net Along With C#
161/181
{
static void Main()
{FileStream file=new
FileStream(C://Myfile.txt,FileMode.Create, FileAccess.Write);
StreameWriter sw=new
StreamWriter(file);sw.WriteLine(Hello);
sw.WriteLine(Welcome);
sw.WriteLine(Bye);
sw.Close();
Console.Writeline(Success);file.Close();
}
}
Sucess
Hello
WelcomeBye
In c drive a note pad
will be created with
the name Myfile.It
will contain thefollowing.
Reading from a file
T d f fil ill d l S R d
-
7/29/2019 Dot Net Along With C#
162/181
To read from a file we will need to use class StreamReader.derived from the TextReader class.
StreamReader sr = new StreamReader(file);
With StreamReader, there are four options for reading from afile: Read, ReadBlock, ReadLine, or ReadToEnd.
string s = sr.ReadToEnd();
ReadToEnd, which just like the title implies, reads the entirefile.
ReadLine, reads each and every line including spaces.
sr.Close();
Using System;
Using System.IO;
Class Fileclass
{
Output:
-
7/29/2019 Dot Net Along With C#
163/181
{
static void Main()
{FileStream file=new FileStream
(C://Myfile.txt,FileMode.Open,
FileAccess.Read);
StreamReader sr=new
StreamReader(file);
string s=sr.ReadToEnd();While(s!=null)
{
Console.WriteLine(s);
s=sr.Readline();
}
sr.close();
file.Close();
}
}
Hello
WelcomeBye
-
7/29/2019 Dot Net Along With C#
164/181
-
7/29/2019 Dot Net Along With C#
165/181
Introduction
Generic Terminology and Syntax
Generic Type
Generic Method
Constraints
Types of Constraints
Generic Class
Contents:
-
7/29/2019 Dot Net Along With C#
166/181
G i i t d t th NET F k th t f
-
7/29/2019 Dot Net Along With C#
167/181
Generics introduce to the .NET Framework the concept of
type parameters, which make it possible to design classesand methods that defer the specification of one or more types
until the class or method is declared and instantiated by
client code.
We can refer to a class, where we don't force it to be related toany specific Type, but we can still perform work with it in a
Type-Safe manner
For example, by using a generic type parameter T you can
write a single class that other client code can use withoutincurring the cost or risk of runtime casts or boxing
operations, as shown here:(Cont)
public class GenericList // Declare the generic class
{ //T=Type Parameter
void Add(T input) { }
}
-
7/29/2019 Dot Net Along With C#
168/181
}
class TestGenericList
{private class ExampleClass { }
static void Main()
{
// Declare a list of type int
GenericList list1 = new GenericList();
// Declare a list of type string
GenericList list2 = new GenericList();
// Declare a list of type ExampleClass
GenericList list3 = newGenericList();
}
}
Generic Terminology and Syntax
Type Parameter:
-
7/29/2019 Dot Net Along With C#
169/181
yp
A type parameter is the core of enabling generic functionality. It is
just like any other parameter in the sense that you pass anargument to it when you use the type or method.
Generic Type and Generic Method:
"generic type" and "generic method." A generic type is a type (class,
struct, delegate, or event) that defines one or more type parameters,
as in the MySample class in Example. A generic method is any
method that defines one or more type parameters, as in the
DoSomething method in Example. It is important to note that
generic methods do not have to be declared within generic types
Example:
public class MySample //generic type
{
public void DoSometing() //generic method
{}
}
Normal Code
class Class1static void Printarray(int[] input)
-
7/29/2019 Dot Net Along With C#
170/181
{
static void Main()
{
int[] intarrey ={ 1, 2, 3, 4, 5, 6};
double[] doublearray ={ 1.2,2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char[] chararray ={ 'a', 'l', 'e',
'x', 'y' };Console.WriteLine("This is Int
Array");
Printarray(intarrey);
Console.WriteLine("This isdouble array");
Printarray(doublearray);
Console.WriteLine("This ischar array");
Printarray(chararray);
}
static void Printarray(int[] input)
{
foreach (int element in input)Console.Write(element+ " " );
Console.WriteLine("\n");
}
static void Printarray(double[] input)
{
foreach (double element in input)Console.Write(element + " ");
Console.WriteLine("\n");
}
static void Printarray(char[] input)
{
foreach (char element in input)
Console.Write(element + " ");
Console.WriteLine("\n");
}
}
OUTPUT
-
7/29/2019 Dot Net Along With C#
171/181
This is Int Array:
1 2 3 4 5 6
This is Double Array:
1.2,2.2,3.3,4.4,5.5,6.6,7.7
This is char Array:
a l e x y
This is lengthy
process and also
time consuming.
Generics Methods
class Class2
-
7/29/2019 Dot Net Along With C#
172/181
class Class2
{
static void Main(){
int[] intarrey ={0,0,0,0,0,0,0 };
double[] doublearray ={ 1.2,2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char[] chararray ={ 'a', 'l', 'e',
'x', 'y' };Console.WriteLine("This is Int
Array");
Printarray(intarrey);
Console.WriteLine("This isdouble array");
Printarray(doublearray);
Console.WriteLine("This ischar array");
Printarray(chararray);
}
static void Printarray(E[] input)
{
foreach (E element in input)
Console.Write(element + " ");
Console.WriteLine("\n");
}
}
Output
-
7/29/2019 Dot Net Along With C#
173/181
This is Int Array:1 2 3 4 5 6
This is Double Array:
1.2,2.2,3.3,4.4,5.5,6.6,7.7
This is char Array:
a l e x y
By using generics
the code is used
for int,double andstring.The length
is reduced.But
we get the same
output.
public class ColMain {public static void Main() {
//create a string version of our genericclass
C l t i t i
Generic Type
-
7/29/2019 Dot Net Along With C#
174/181
public class Col
{
T t;
public T Val
{
get
{return t;
}
set
{
t=value;
}
}
}
Col mystring = newCol();
mystring.Val = "hello"; //set the value
System.Console.WriteLine(mystring.Val);System.Console.WriteLine(mystring.Val.GetType());
//create another instance of ourgeneric class, using a different type
Col myint = new Col();
//load the value
myint.Val = 5;
//output the value
System.Console.WriteLine(myint.Val);
//output the value's typeSystem.Console.WriteLine(myint.Val.GetType());
}
}
Generic Type
-
7/29/2019 Dot Net Along With C#
175/181
The class name col indicates that this is of generic
type. is called the Type parameter.
Variable declaration T t member variable with type of T.
The actual value of T will be specified during construction ofclass(it will actually gets inserted by the CLR automatically).
The actual value of T can be specified while creating the
object as shown in the example.
Constraints
-
7/29/2019 Dot Net Along With C#
176/181
Constraints are a feature of .NET generics that enable the
creator of a generic to specify that only certain types may be
passed in as type arguments to his generic.
Constraints solve a problem that involves the usage of type
parameters within a generic type.
Constraints are applied by using the contextual keyword
where.
More than one constraints can be added using whereKeyword.
Types of Constraints
Where T: struct
-
7/29/2019 Dot Net Along With C#
177/181
Where T: struct
The type argument must be a value type. Any value type except Nullable can be
specified.
Where T : class
The type argument must be a reference type; this applies also to any class,
interface, delegate, or array type.
Where T : new()
The type argument must have a public parameterless constructor. When used
together with other constraints, the new() constraint must be specified last.
Where T :
The type argument must be or derive from the specified base class.
Where T :
The type argument must be or implement the specified interface. Multiple
interface constraints can be specified. The constraining interface can also begeneric.
Where T : U
The type argument supplied for T must be or derive from the argument supplied
for U. This is called a naked type constraint.
class Factory where U : new(){
publicstatic U GetNew()OUTPUT:
-
7/29/2019 Dot Net Along With C#
178/181
{
returnnew U();}
}
class Program
{
staticvoid Main()
{
int i = Factory.GetNew();
object obj =Factory.GetNew();
Console.WriteLine(i);
Console.WriteLine(obj);
}
}
0
object
// Here, 'i' is equal to 0and 'obj' referencesan instance of theclass 'object'.
Generic Class Nongeneric Counterpart
in System.Collections
Meaning in Life
Collection CollectionBase The basis for a generic collection
-
7/29/2019 Dot Net Along With C#
179/181
Comparer Comparer Compares two generic objectsfor equality
Dictionary Hashtable A generic collection of
name/value pairs
List ArrayList A dynamically resizable list of
items
Queue Queue A generic implementation of afirst-in, first-out (FIFO) list
Stack Stack A generic implementation of a
last-in, first-out (LIFO) list
SortedDictionary SortedList A generic implementation of a
sorted set of name/value pairs
ReadOnlyCollection ReadOnlyCollectionBase A generic implementation of a set
of read-only items
Example
using System Collections Generic; using a generic List collection is
-
7/29/2019 Dot Net Along With C#
180/181
using System.Collections.Generic;
public class MainClass{
static void Main()
{
List myInts = new List();
myInts.Add(1);myInts.Add(2);
myInts.Add(3);
for (int i = 0; i
-
7/29/2019 Dot Net Along With C#
181/181
The End