SlideShare a Scribd company logo
Unit 4
Book 5- E.Balguruswamy,
Programming in C#, Tata Mc-Graw
Hill, 2nd Edition
1
Overview of C#
• Microsoft named their new language as C#, they wanted a better ,
smarter, sharper language than its ancestors C and C++.
• Developed only for .NET platform which provide tools and services that
fully exploit both computing and communication.
• Many features are incorporated from Java.
• Provides one-stop coding approach to maintenance.
• C# is used to develop two categories of programs
– Executable application programs
– Component libraries
• Executable programs are written to carry out certain tasks and require the
method Main in one the classes.
• Component libraries do not require a Main declaration, because they are
stand alone application.
2
C# programs
Executable
programs
Library
programs
CLR
output
application
programs
CLR
output
3
C# and .net
• C# is a new programming language introduced in.net
• With C# developers can quickly implement applications and
components using built-in capabilities of the .net framework.
• C# code is managed by CLR it becomes safer than C++
• Benefits of CLR
– Interoperability with other languages
– Enhanced security
– Versioning support
– Debugging support
– Automatic garbage collection
– XML support for web based application
4
Similarities and differences from JAVA
• C# complier produces an executable code.
• C# has more primitive data types
• C# data types are objects.
• Arrays are declared differently in C#
• Java uses static final to declare a class constant while C# uses
const
• java will have one public class in each file, while c# allows any
file arrangements.
• C# supports the struct type and Java does not.
• C# provides better versioning than java
5
• In java parameters are always passed by value, C# allows
parameters to be passed by reference by using ref keyword.
• In java, the switch statement can only have integer
expression, while C# supports either integer or string
expression.
• There is no labeled break statement in C#, goto is used to
achieve this.
• C# uses is operator instead of instanceof operator in Java
• C# allows a variable number of parameters using the params
keywords.
• C# provides fourth type of iteration called foreach.
6
A simple C# program
• Displays a line of text.
class sampleone
{
public staic void Main()
{
System.Console.WriteLine(“C# is sharper than C++”);
}
}
7
1. class declaration
– class is object-oriented construct
– class is the keyword and declares a new class.
– sampleone is a C# identifier, specifies the name of the class to be
defined.
2. Braces
– C# is block-structured language, enclosed by braces { and }
– Every class definition begins with ‘{‘ and ends with ‘}’
3. Main
– Must include this method in one of the classes.
– Starting point for executing the program.
– Can have any no. of classes but only one main method
8
• Has got keywords public, static , void
• public
– Is an access modifier, tells the C# complier that the main method is
accessible by any one.
• static
– Declares main method is global
– Can be called without creating an instance of the class.
• void
– States that main method does not return any value
9
4. Output line
– System.Console.WriteLine(“C# is sharper than C++”);
– Similar to java statement, printf() of C, cout<< of C++
– Writeline method is a static method of Console class, located in a
namespace System.
– Prints a line C# is sharper than C++
– Every statement in C# should end with a semi-colon
5. Executing the program
– After creating the source code, save with .cs file extension in your
folder in your system. Eg. Sampleone.cs
– For compiling the program, perform csc sampleone.cs
– Executable file(IL code), run by name, sample
10
Transformation of source code to output
C# code
IL code
Native machine
code
output
C# compilation
JIT compilation
Execution
(.cs file)
(.exe file)
11
Providing interactive input
• Using assignment statement
• Through command line arguments
using System;
class SampleEight
{
public static void Main()
{
Console.Write(“Enter your name”);
String name=Console.ReadLine();
Console.WriteLine(“Hello” +=name);
}
}
12
Output
Enter your name: John
Hello John
Using mathematical functions
class SampleNine
{
public static void Main()
{
double x=5.0;
double y;
y=Math.sqrt(x);
Console.WriteLine(“y = “+y);
}
}
13
Output
Y=2.23606
Compile time errors
• Real life applications consists of large number of statements
and have complex logic.
• They will have errors in them.
• Two types of errors
– Syntax errors
– Logic errors
• Syntax errors is caught by the complier and logic errors should
be eliminated by testing the program logic carefully.
• When compiler cannot interpret what we want to convey,
result is syntax error.
• Complier detects such an error and displays an appropriate
error message
14
//program with syntax errors
using systom; //error
class Sampleten
{
public static void main() //error
{
Console.WriteLine(“y = “+y) //error
}
}
15
• The complier could not locate a namespace called “systom”
and therefore produces an error message and then stops
compiling.
• Error message consists of
• Name of the file being complied (error.cs)
• Linenumber and column position of the error (2.7)
• Error code defined by the complier (CS0234)
• Short description about the error.
• Eg: error.cs(2.7):error cs0234: the type or namespace name
‘systom’ does not exist in class or namespace.
16
17
Program structure
Main method section
Documentation section
Using directive section
Interfaces section
Classes section
optional
optional
optional
optional
essential
Programming coding style
• C# is freeform language
• No indentation required , so that program works properly.
• But this is bad programming.
• Eg.
Console.WriteLine(“Enter your name”);
• Can be written as
Console.Write
(“Enter your name”);
• Or
Console.Write
(
“Enter your name”
);
18
Decision making
• If statement has different forms
– Simple if statement
– if..else statement
– nested if..else statement
– else if ladder
• Switch statement
• ?: operator
19
Simple if statement
if (boolean-expression)
{
Statement-block;
}
Statement x;
20
Boolean
expression
Statement block
false
true
entry
Statement x
Next Statement
The if..else statement
if (boolean-expression)
{
true-block Statement(s);
}
else
{
false-block statement(s);
}
Statement x;
21
Boolean
expression
True block Statement
true
entry
Statement x
Next Statement
False block Statement
false
Nested if..else statements
if(test condition1)
{
if(test condition2)
{
statement 1;
}
else
{
statement2;
}
}
else
{
statement 3;
}
statement x;
22
Test
condition1
Statement 3
false
entry
Statement x
Test
condition2
true
false
Statement 2
true
Statement 1
Else if ladder
if(condition1)
statement1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
…
else if
default-satement;
statement-x;
23
Switch operator
switch (expression)
{
case value-1: block-1;
break;
case-value-2:block-2;
break;
…
default: default-block;
break;
}
statement-x;
24
?: operator
• Conditional operator
• conditional expression ? expression1:expression2
• Conditional expression is evaluated first
• If result is true, expression 1 is evaluated
• If result is false, expression2 is evaluated
• Eg:
if(x<0)
flag=0;
else
flag=1;
• Can be written as
flag=(x<0)?0:1
25
Boxing and unboxing
• Methods are invoked using objects.
• Value types like int and long are not objects , we cannot use
them to call methods.
• Can be achieved using a technique called boxing.
• Boxing means the conversion of value type on the stack to a
object type on the heap.
• Unboxing means conversion of object type back into value
type
26
boxing
• When the complier finds a value type where it needs a
reference type, it creates an object ‘box’ into which it places
the value of the value type.
int m=100;
Object om=m; //creates a box to hold m
• On execution, it creates a temporary reference_type ‘box’ to
old the object on heap.
• Boxing operation creates a copy of the value of m integer to
object om.
27
unboxing
• Unboxing is the process of converting the object type back to
value type.
• Unboxing is possible only for previously boxed variable.
int m=10;
object om=m; //box m
int n= (int) om;
• When unboxing , c# checks that the value type requested is
actually stored in the object under conversion. Only if it is,
the value is unboxed.
• We should ensure that, the value type is large enough to hold
the value of the object. Otherwise it may result in run-time
error.
28
Declaring methods
modifiers type methodname (formal-parameter-list)
{
method_body
}
• Five parts
– Name of the method
– Type of the value the method returns
– List of parameters
– Body of the method
– Method modifiers
29
int product(int x,int y)
{
int m=x*y;
return(m);
}
Invoking methods
• The process of activating a
method is known as
invoking or calling.
• Done using dot operator
• objectname.methodname(a
ctual-parameter-list);
• The values of the actual
parameters are assigned to
the formal parameters at
the time of invocation.
using System;
class method
{
int cube(int x)
{
return(x*x*x);
}
}
class methodtest
{
public static void Main()
{
method m=new method();
int y=m.cube(5);
Console.WriteLine(y);
}
}
30
Invoking a static method
using System;
class staticmethod
{
public static void Main()
{
double y=square(4);
Console.WriteLine(y);
}
static double square(int x)
{
return(x*x);
}
}
31
Pass by value
using System;
class method
{
static void func(int m)
{
m=m+10;
Console.Write(m);
}
}
class methodtest
{
public static void Main()
{
int x=100;
func(x);
Console.WriteLine(x);
}
}
32
Pass by reference
• ref keyword is used.
using System;
class passbyref
{
static void swap( ref int x, ref int y)
{
int temp=x;
x=y;
y=temp;
}
public static void Main()
{
int m=100,n=200;
console.writeline(“before swapping:”);
console.writeline(“m=“+m);
console.writeline(“n=“+n);
swap(ref m,ref n);
console.writeline(“after swapping”);
console.writeline(“m=“+m);
console.writeline(“n=“+n);
}
}
33
Output parameters
• Using out keyword, to return values to the called functions.
using System;
class staticmethod
{
public static void Main()
{
int m,n;
square(4,out m,int n);
Console.WriteLine(m);
C.W(n);
}
static double square(int x, out int y, out int z)
{
y=x*x;
Z=x*x*x;
}
}
34
Variable parameter list
using System;
class params
{
static void parray(params int [] arr)
{
C.W(“array elemets are:”);
foreach(int i in arr)
C.W(“ “ +i);
}
public static void main()
{
int x={11,22,33};
parray(x);
parray();
parray(100,200);
}
}
35
Methods overloading
using System;
class overloading
{
public static void main()
{
C.W(volume(10));
C.W(volume(2.5 F,8));
C.W(volume(100L,75,15));
}
static int volume(int x)
{
return (x*x*x); //cube
}
static double volume(float r,int h)
{
return(3.14*r*r*h); //cylinder
}
static long volume( long l,int b,int h)
{
return(l*b*h); //box
}
36
Defining a class
class classname
{
[variables declaration;]
[methods declaration;]
}
• Class is user defined data type with a template that serves to
define its properties
• Class is the keyword, classname is the valid C# identifier
• Everything inside [ ] is optional.
37
Adding variables
• Data is encapsulated in a class by placing data fields inside
the body of the class definition.
• These variables are called instance variables because they are
created whenever a object of the class of instantiated.
class rectangle
{
int length;
int width;
}
38
Adding methods
• A class with only data fields and no methods that operate on that
data has no life.
type methodname (parameter-list)
{
method-body;
}
class rectangle
{
int length;
int width;
public void getdata(int x,int y)
{
length=x;
length=y;
}
}
39
Member access modifiers
• Private,Public,Protected,Internal,Protected internal
• By default it is private
class visiblity
{
public int x;
internal int y;
protected double d;
float p; //private by default
}
40
Creating objects
• Objects are created in C# using the new operator.
• The new operator creates an object of the specified class and
returns a reference to that object.
• rectangle rect1; //declare
• rec1=new rectangle(); //instantiate
• rectangle()is default constructor of the class.
41
Accessing class members
• objectname.variablename;
• objectname.methodname(parameter_list);
• rect1.length=15;
• rect1.width=10;
• Constructors:
• It enables an object to initialize itself when it is created.
• Same name as that of the class.
• Do not have any return type, not even void.
42
Overloaded constructors
• Methods have same name,
different parameter list and
different definitions method
overloading.
• Used to perform simple tasks
which requires different types of
parameter list.
• Also known as polymorphism.
• Each parameter list should be
unique.
• rect r1=new rect(10,20);
• rect r2=new rect(10);
class rectangle
{
public int length;
public int width;
public rectangle(int x,int y)
{
length=x; width=y;
}
public rectangle(int x)
{
length=width=x;
}
public int area()
{
return(length*width);
}
}
43
Static constructors
• Called before any objects of the class is created.
• Used to assign initial values to static data
members.
class abc{
static abc(){
..
}
..
}
44
• Private constructors
– All declarations must be contained in the class
– Creating objects using such classes may be prevented by adding a
private constructor to the class.
• Copy constructors
– Creates an object by copying variables from another object.
• C# does not provide a copy constructor. We have to define.
public item(item item)
{
code=item.code;
price=item.price;
}
• Copy constructor is invoked by instantiating an object of type
Item and passing it object to be copied.
• Item item2=new item(item1);
45
deconstructors
• Opposite of constructors.
• Name is same as that of the constructor , preceded by ~.
class fun
{…
~fun(){..}
}
• C# manages the memory dynamically and uses a garbage
collector, executes all deconstructors on exit.
• The process of calling a deconstructors when an object is
reclaimed by the garbage collector is called finalization.
46
This reference
class integers
{
int x;
int y;
public void setxy(int x,inty)
{
this.x=x;
this.y=y;
}
…
}
47
Nesting of classes
public class outer
{
…. // members of outer class
public class inner
{
….//members of inner class
}
}
48
Constant members
• Allows declaration of data fields of a class as constant.
• public const int size=100;
• Member size is initialized 100 during compilation , it cannot
be changed later.
• Any attempt done to assign a value to it, will result in
compilation error.
• Const members are implicitly static.
• public static const int size=100;
• Will produce compile time error, we cannot declare explicitly
using static
49
read-only members
• Using readonly modifier, we can set the value of the member
using a constructor method, cannot be modified later.
• Declared as static fields or instance fields.
class numbers
{
public readonly int m;
public static readonly int n;
public numbers(int x)
{ m=x; }
static numbers()
{ n=100; }
}
50
properties
• Accessor methods to
access the data members
• Mutator method  to set
the value of the data
members
• Drawback:
• We have to code accessor
methods manually
• Uses should remember that
they have to use accessor
methods to work with data
members
using system;
class number
{
private int number;
public int anumber; //property
{
get
return number;
set
number=value;
}
}
class propertytest
{
public void static main()
{
number n=new number();
n.anumber=100;
int m=n.anumber;
Console.WriteLine(“Number=”+m);
}
} 51
indexers
• They are location indicators
• Used to access class objects just like accessing elements in array
• Useful when class is container of other classes.
• The indexer takes an index argument and looks like an array
• The indexer is declared using name this.
• Implemented using get and set accessors for the [] operator.
public double this[int idx]
{
get
{ //return desired data }
set
{//set desired data }
}
52
Defining an interface
• it contains one or more methods, properties, indexers, events
but none of them are implemented in the interface itself.
interface interface_name
{
member declarations;
}
eg. interface show
{
void display();
}
53
Extending an interface
Interface l1
{
….
}
interface l2
{
….
}
interface l3:l2,l1
{
….
}
54
Interface name2:name1
{
members of name2
}
• Eg:
interface addition
{
int add(intx,int y);
}
interface compute:addition
{
int sub(int x, int y);
}
Implementing interfaces
class classname :interfacename
{
body of classname
}
• Here classname implements the interfacename
class a:b,l1,l2
{
…
}
• Where B is the base class and l1,l2 are the interfaces
55
Abstract class and interfaces
interface a
{
void method();
}
abstract class b:a
{
..
public abstract void method();
}
56
Delegates
• Dictionary meaning of “Delegate” means a person acting for
another person.
• In C# it means a method acting for another method.
• It is used to invoke a method that has been encapsulated into
it at time of its creation.
• Has four steps
– Delegate declaration
– Delegate methods definition
– Delegate instantiation
– Delegate invocation
57
Delegate declaration
• A delegate declaration defines a class using that
System.Delagate base class.
• Delegate methods are any functions whose signature matches
the delegate signature exactly.
• modifier delegate return-type delegate-name(parameters);
• Delegate may be defined in the following places
– Inside a class
– Outside a class
– As top level object in a namespace.
• Delegates are implicitly sealed.
58
Delegate methods
• Methods whose references are encapsulated into a delegate
instance are known as delegate methods or callable entities.
• The signature and return type of the delegate methods must
exactly match the signature and return type of the delegate.
• They do not care
– What type of object the method is being called against.
– Whether the method is static or instance method.
59
Delegate instantiation
• New delegate-type(expression)
• Delegate-type is the name of the delegate declared earlier whose
object is to be created.
• Expression must be method name or value of delegate type.
delegate int productdelegate(int x,int y);
class delegate
{
static int product (int a,int b)
return (a*b);
//delegate instantiation
productdelegate p=new productdelegate(product);
}
60
Delegate invocation
• delegate_object(parameter_list)
• If the invocation return void, the result is nothing and
therefore it cannot be used as an operand of any operator.
• Eg. delegate(x,y);
• If a method returns a value, then it can be used as an operand
of any operator.
• Eg. double result= delegate(2.56,45.73);
61
Events
• An event is a delegate type class member that is used by the
object or class to provide a notification to other objects that
an event has occurred.
• The client object can act on an event by adding an event
handler to the event.
• modifier event type event-name;
• Modifiers can be static,virtual,override,abstarct,sealed.
• Typedelegate.
• Eg: public event EventHandler click;
• EventHandler is a delegate and click is an event.
62

More Related Content

PPT
Difference between Java and c#
ODP
Ppt of c vs c#
PDF
Difference between java and c#
PPTX
Introduction to C programming
ODP
Ppt of c++ vs c#
PPTX
C++ vs C#
PDF
Advanced C Language for Engineering
PPSX
Complete C++ programming Language Course
Difference between Java and c#
Ppt of c vs c#
Difference between java and c#
Introduction to C programming
Ppt of c++ vs c#
C++ vs C#
Advanced C Language for Engineering
Complete C++ programming Language Course

What's hot (20)

PPTX
Introduction Of C++
PPTX
C programming interview questions
PPTX
CSharp Presentation
PPT
2. data, operators, io
PPTX
C# in depth
PPTX
C++ programming language basic to advance level
PDF
Learning the C Language
PPT
C++ Programming Course
PPT
01 c++ Intro.ppt
PDF
Deep C
ODP
(2) c sharp introduction_basics_part_i
PPTX
PDF
C notes.pdf
DOCX
PPT
The smartpath information systems c plus plus
PDF
C++ Training
PDF
Hands-on Introduction to the C Programming Language
PPT
C++ polymorphism
PPTX
Overview of c++ language
Introduction Of C++
C programming interview questions
CSharp Presentation
2. data, operators, io
C# in depth
C++ programming language basic to advance level
Learning the C Language
C++ Programming Course
01 c++ Intro.ppt
Deep C
(2) c sharp introduction_basics_part_i
C notes.pdf
The smartpath information systems c plus plus
C++ Training
Hands-on Introduction to the C Programming Language
C++ polymorphism
Overview of c++ language
Ad

Viewers also liked (20)

PPT
Control statements
PPTX
Chap2 comp architecture
PPT
Data types and Operators
PPTX
Java-Unit 3- Chap2 exception handling
PPTX
Chap2 exception handling
PPTX
Chap2 class,objects
PPTX
Chap1 array
PPTX
Chap1 packages
PPTX
output devices
PPTX
Chap2 class,objects contd
PPTX
FIT-Unit3 chapter 1 -computer program
PPT
Using Input Output
PDF
Module1 part2
PPTX
java-Unit4 chap2- awt controls and layout managers of applet
PPTX
Chap3 inheritance
PDF
Module1 Mobile Computing Architecture
PPTX
Chap3 primary memory
PPTX
Chap3 multi threaded programming
PPTX
Chap2 input devices
PPT
Chap1 computer basics
Control statements
Chap2 comp architecture
Data types and Operators
Java-Unit 3- Chap2 exception handling
Chap2 exception handling
Chap2 class,objects
Chap1 array
Chap1 packages
output devices
Chap2 class,objects contd
FIT-Unit3 chapter 1 -computer program
Using Input Output
Module1 part2
java-Unit4 chap2- awt controls and layout managers of applet
Chap3 inheritance
Module1 Mobile Computing Architecture
Chap3 primary memory
Chap3 multi threaded programming
Chap2 input devices
Chap1 computer basics
Ad

Similar to C#unit4 (20)

PPT
Synapseindia dot net development
PPT
CSharp_02_LanguageOverview_andintroduction
PPT
Csharp_mahesh
PDF
A tour of C# - Overview _ Microsoft Learn.pdf
PDF
C# c# for beginners crash course master c# programming fast and easy today
PPTX
c# at f#
PPTX
C# AND F#
DOCX
C-sharping.docx
PPTX
Notes(1).pptx
PPTX
Cordovilla
PPTX
Introduction to C#
PPTX
1. Introduction to C# Programming Langua
PDF
Understanding C# in .NET
PPTX
csharp_dotnet_adnanreza.pptx
PDF
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
DOCX
Event Driven Programming in C#.docx
PPT
20 intro-to-csharp
PPTX
A POWERPOINT PRESENTATION ABOUT INTRODUCTION TO C#
DOCX
csharp.docx
Synapseindia dot net development
CSharp_02_LanguageOverview_andintroduction
Csharp_mahesh
A tour of C# - Overview _ Microsoft Learn.pdf
C# c# for beginners crash course master c# programming fast and easy today
c# at f#
C# AND F#
C-sharping.docx
Notes(1).pptx
Cordovilla
Introduction to C#
1. Introduction to C# Programming Langua
Understanding C# in .NET
csharp_dotnet_adnanreza.pptx
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
Event Driven Programming in C#.docx
20 intro-to-csharp
A POWERPOINT PRESENTATION ABOUT INTRODUCTION TO C#
csharp.docx

More from raksharao (17)

PPTX
Unit 1-logic
PPTX
Unit 1 rules of inference
PPTX
Unit 1 quantifiers
PPTX
Unit 1 introduction to proofs
PPTX
Unit 7 verification &amp; validation
PPTX
Unit 6 input modeling problems
PPTX
Unit 6 input modeling
PPTX
Unit 5 general principles, simulation software
PPTX
Unit 5 general principles, simulation software problems
PPTX
Unit 4 queuing models
PPTX
Unit 4 queuing models problems
PPTX
Unit 3 random number generation, random-variate generation
PPTX
Unit 1 introduction contd
PPTX
Unit 1 introduction
PPTX
java Unit4 chapter1 applets
PPTX
FIT-Unit3 chapter2- Computer Languages
PPTX
Chap1 secondary storage
Unit 1-logic
Unit 1 rules of inference
Unit 1 quantifiers
Unit 1 introduction to proofs
Unit 7 verification &amp; validation
Unit 6 input modeling problems
Unit 6 input modeling
Unit 5 general principles, simulation software
Unit 5 general principles, simulation software problems
Unit 4 queuing models
Unit 4 queuing models problems
Unit 3 random number generation, random-variate generation
Unit 1 introduction contd
Unit 1 introduction
java Unit4 chapter1 applets
FIT-Unit3 chapter2- Computer Languages
Chap1 secondary storage

Recently uploaded (20)

PPT
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
PDF
Visual Aids for Exploratory Data Analysis.pdf
PDF
86236642-Electric-Loco-Shed.pdf jfkduklg
PPT
Occupational Health and Safety Management System
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
introduction to high performance computing
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PPTX
Artificial Intelligence
PPTX
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
PPTX
Information Storage and Retrieval Techniques Unit III
PPTX
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
PDF
737-MAX_SRG.pdf student reference guides
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
Safety Seminar civil to be ensured for safe working.
PDF
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PDF
Analyzing Impact of Pakistan Economic Corridor on Import and Export in Pakist...
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
Visual Aids for Exploratory Data Analysis.pdf
86236642-Electric-Loco-Shed.pdf jfkduklg
Occupational Health and Safety Management System
R24 SURVEYING LAB MANUAL for civil enggi
introduction to high performance computing
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Artificial Intelligence
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
Information Storage and Retrieval Techniques Unit III
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
737-MAX_SRG.pdf student reference guides
Automation-in-Manufacturing-Chapter-Introduction.pdf
Safety Seminar civil to be ensured for safe working.
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Fundamentals of safety and accident prevention -final (1).pptx
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
Categorization of Factors Affecting Classification Algorithms Selection
Analyzing Impact of Pakistan Economic Corridor on Import and Export in Pakist...

C#unit4

  • 1. Unit 4 Book 5- E.Balguruswamy, Programming in C#, Tata Mc-Graw Hill, 2nd Edition 1
  • 2. Overview of C# • Microsoft named their new language as C#, they wanted a better , smarter, sharper language than its ancestors C and C++. • Developed only for .NET platform which provide tools and services that fully exploit both computing and communication. • Many features are incorporated from Java. • Provides one-stop coding approach to maintenance. • C# is used to develop two categories of programs – Executable application programs – Component libraries • Executable programs are written to carry out certain tasks and require the method Main in one the classes. • Component libraries do not require a Main declaration, because they are stand alone application. 2
  • 4. C# and .net • C# is a new programming language introduced in.net • With C# developers can quickly implement applications and components using built-in capabilities of the .net framework. • C# code is managed by CLR it becomes safer than C++ • Benefits of CLR – Interoperability with other languages – Enhanced security – Versioning support – Debugging support – Automatic garbage collection – XML support for web based application 4
  • 5. Similarities and differences from JAVA • C# complier produces an executable code. • C# has more primitive data types • C# data types are objects. • Arrays are declared differently in C# • Java uses static final to declare a class constant while C# uses const • java will have one public class in each file, while c# allows any file arrangements. • C# supports the struct type and Java does not. • C# provides better versioning than java 5
  • 6. • In java parameters are always passed by value, C# allows parameters to be passed by reference by using ref keyword. • In java, the switch statement can only have integer expression, while C# supports either integer or string expression. • There is no labeled break statement in C#, goto is used to achieve this. • C# uses is operator instead of instanceof operator in Java • C# allows a variable number of parameters using the params keywords. • C# provides fourth type of iteration called foreach. 6
  • 7. A simple C# program • Displays a line of text. class sampleone { public staic void Main() { System.Console.WriteLine(“C# is sharper than C++”); } } 7
  • 8. 1. class declaration – class is object-oriented construct – class is the keyword and declares a new class. – sampleone is a C# identifier, specifies the name of the class to be defined. 2. Braces – C# is block-structured language, enclosed by braces { and } – Every class definition begins with ‘{‘ and ends with ‘}’ 3. Main – Must include this method in one of the classes. – Starting point for executing the program. – Can have any no. of classes but only one main method 8
  • 9. • Has got keywords public, static , void • public – Is an access modifier, tells the C# complier that the main method is accessible by any one. • static – Declares main method is global – Can be called without creating an instance of the class. • void – States that main method does not return any value 9
  • 10. 4. Output line – System.Console.WriteLine(“C# is sharper than C++”); – Similar to java statement, printf() of C, cout<< of C++ – Writeline method is a static method of Console class, located in a namespace System. – Prints a line C# is sharper than C++ – Every statement in C# should end with a semi-colon 5. Executing the program – After creating the source code, save with .cs file extension in your folder in your system. Eg. Sampleone.cs – For compiling the program, perform csc sampleone.cs – Executable file(IL code), run by name, sample 10
  • 11. Transformation of source code to output C# code IL code Native machine code output C# compilation JIT compilation Execution (.cs file) (.exe file) 11
  • 12. Providing interactive input • Using assignment statement • Through command line arguments using System; class SampleEight { public static void Main() { Console.Write(“Enter your name”); String name=Console.ReadLine(); Console.WriteLine(“Hello” +=name); } } 12 Output Enter your name: John Hello John
  • 13. Using mathematical functions class SampleNine { public static void Main() { double x=5.0; double y; y=Math.sqrt(x); Console.WriteLine(“y = “+y); } } 13 Output Y=2.23606
  • 14. Compile time errors • Real life applications consists of large number of statements and have complex logic. • They will have errors in them. • Two types of errors – Syntax errors – Logic errors • Syntax errors is caught by the complier and logic errors should be eliminated by testing the program logic carefully. • When compiler cannot interpret what we want to convey, result is syntax error. • Complier detects such an error and displays an appropriate error message 14
  • 15. //program with syntax errors using systom; //error class Sampleten { public static void main() //error { Console.WriteLine(“y = “+y) //error } } 15
  • 16. • The complier could not locate a namespace called “systom” and therefore produces an error message and then stops compiling. • Error message consists of • Name of the file being complied (error.cs) • Linenumber and column position of the error (2.7) • Error code defined by the complier (CS0234) • Short description about the error. • Eg: error.cs(2.7):error cs0234: the type or namespace name ‘systom’ does not exist in class or namespace. 16
  • 17. 17 Program structure Main method section Documentation section Using directive section Interfaces section Classes section optional optional optional optional essential
  • 18. Programming coding style • C# is freeform language • No indentation required , so that program works properly. • But this is bad programming. • Eg. Console.WriteLine(“Enter your name”); • Can be written as Console.Write (“Enter your name”); • Or Console.Write ( “Enter your name” ); 18
  • 19. Decision making • If statement has different forms – Simple if statement – if..else statement – nested if..else statement – else if ladder • Switch statement • ?: operator 19
  • 20. Simple if statement if (boolean-expression) { Statement-block; } Statement x; 20 Boolean expression Statement block false true entry Statement x Next Statement
  • 21. The if..else statement if (boolean-expression) { true-block Statement(s); } else { false-block statement(s); } Statement x; 21 Boolean expression True block Statement true entry Statement x Next Statement False block Statement false
  • 22. Nested if..else statements if(test condition1) { if(test condition2) { statement 1; } else { statement2; } } else { statement 3; } statement x; 22 Test condition1 Statement 3 false entry Statement x Test condition2 true false Statement 2 true Statement 1
  • 23. Else if ladder if(condition1) statement1; else if(condition 2) statement 2; else if(condition 3) statement 3; … else if default-satement; statement-x; 23
  • 24. Switch operator switch (expression) { case value-1: block-1; break; case-value-2:block-2; break; … default: default-block; break; } statement-x; 24
  • 25. ?: operator • Conditional operator • conditional expression ? expression1:expression2 • Conditional expression is evaluated first • If result is true, expression 1 is evaluated • If result is false, expression2 is evaluated • Eg: if(x<0) flag=0; else flag=1; • Can be written as flag=(x<0)?0:1 25
  • 26. Boxing and unboxing • Methods are invoked using objects. • Value types like int and long are not objects , we cannot use them to call methods. • Can be achieved using a technique called boxing. • Boxing means the conversion of value type on the stack to a object type on the heap. • Unboxing means conversion of object type back into value type 26
  • 27. boxing • When the complier finds a value type where it needs a reference type, it creates an object ‘box’ into which it places the value of the value type. int m=100; Object om=m; //creates a box to hold m • On execution, it creates a temporary reference_type ‘box’ to old the object on heap. • Boxing operation creates a copy of the value of m integer to object om. 27
  • 28. unboxing • Unboxing is the process of converting the object type back to value type. • Unboxing is possible only for previously boxed variable. int m=10; object om=m; //box m int n= (int) om; • When unboxing , c# checks that the value type requested is actually stored in the object under conversion. Only if it is, the value is unboxed. • We should ensure that, the value type is large enough to hold the value of the object. Otherwise it may result in run-time error. 28
  • 29. Declaring methods modifiers type methodname (formal-parameter-list) { method_body } • Five parts – Name of the method – Type of the value the method returns – List of parameters – Body of the method – Method modifiers 29 int product(int x,int y) { int m=x*y; return(m); }
  • 30. Invoking methods • The process of activating a method is known as invoking or calling. • Done using dot operator • objectname.methodname(a ctual-parameter-list); • The values of the actual parameters are assigned to the formal parameters at the time of invocation. using System; class method { int cube(int x) { return(x*x*x); } } class methodtest { public static void Main() { method m=new method(); int y=m.cube(5); Console.WriteLine(y); } } 30
  • 31. Invoking a static method using System; class staticmethod { public static void Main() { double y=square(4); Console.WriteLine(y); } static double square(int x) { return(x*x); } } 31
  • 32. Pass by value using System; class method { static void func(int m) { m=m+10; Console.Write(m); } } class methodtest { public static void Main() { int x=100; func(x); Console.WriteLine(x); } } 32
  • 33. Pass by reference • ref keyword is used. using System; class passbyref { static void swap( ref int x, ref int y) { int temp=x; x=y; y=temp; } public static void Main() { int m=100,n=200; console.writeline(“before swapping:”); console.writeline(“m=“+m); console.writeline(“n=“+n); swap(ref m,ref n); console.writeline(“after swapping”); console.writeline(“m=“+m); console.writeline(“n=“+n); } } 33
  • 34. Output parameters • Using out keyword, to return values to the called functions. using System; class staticmethod { public static void Main() { int m,n; square(4,out m,int n); Console.WriteLine(m); C.W(n); } static double square(int x, out int y, out int z) { y=x*x; Z=x*x*x; } } 34
  • 35. Variable parameter list using System; class params { static void parray(params int [] arr) { C.W(“array elemets are:”); foreach(int i in arr) C.W(“ “ +i); } public static void main() { int x={11,22,33}; parray(x); parray(); parray(100,200); } } 35
  • 36. Methods overloading using System; class overloading { public static void main() { C.W(volume(10)); C.W(volume(2.5 F,8)); C.W(volume(100L,75,15)); } static int volume(int x) { return (x*x*x); //cube } static double volume(float r,int h) { return(3.14*r*r*h); //cylinder } static long volume( long l,int b,int h) { return(l*b*h); //box } 36
  • 37. Defining a class class classname { [variables declaration;] [methods declaration;] } • Class is user defined data type with a template that serves to define its properties • Class is the keyword, classname is the valid C# identifier • Everything inside [ ] is optional. 37
  • 38. Adding variables • Data is encapsulated in a class by placing data fields inside the body of the class definition. • These variables are called instance variables because they are created whenever a object of the class of instantiated. class rectangle { int length; int width; } 38
  • 39. Adding methods • A class with only data fields and no methods that operate on that data has no life. type methodname (parameter-list) { method-body; } class rectangle { int length; int width; public void getdata(int x,int y) { length=x; length=y; } } 39
  • 40. Member access modifiers • Private,Public,Protected,Internal,Protected internal • By default it is private class visiblity { public int x; internal int y; protected double d; float p; //private by default } 40
  • 41. Creating objects • Objects are created in C# using the new operator. • The new operator creates an object of the specified class and returns a reference to that object. • rectangle rect1; //declare • rec1=new rectangle(); //instantiate • rectangle()is default constructor of the class. 41
  • 42. Accessing class members • objectname.variablename; • objectname.methodname(parameter_list); • rect1.length=15; • rect1.width=10; • Constructors: • It enables an object to initialize itself when it is created. • Same name as that of the class. • Do not have any return type, not even void. 42
  • 43. Overloaded constructors • Methods have same name, different parameter list and different definitions method overloading. • Used to perform simple tasks which requires different types of parameter list. • Also known as polymorphism. • Each parameter list should be unique. • rect r1=new rect(10,20); • rect r2=new rect(10); class rectangle { public int length; public int width; public rectangle(int x,int y) { length=x; width=y; } public rectangle(int x) { length=width=x; } public int area() { return(length*width); } } 43
  • 44. Static constructors • Called before any objects of the class is created. • Used to assign initial values to static data members. class abc{ static abc(){ .. } .. } 44
  • 45. • Private constructors – All declarations must be contained in the class – Creating objects using such classes may be prevented by adding a private constructor to the class. • Copy constructors – Creates an object by copying variables from another object. • C# does not provide a copy constructor. We have to define. public item(item item) { code=item.code; price=item.price; } • Copy constructor is invoked by instantiating an object of type Item and passing it object to be copied. • Item item2=new item(item1); 45
  • 46. deconstructors • Opposite of constructors. • Name is same as that of the constructor , preceded by ~. class fun {… ~fun(){..} } • C# manages the memory dynamically and uses a garbage collector, executes all deconstructors on exit. • The process of calling a deconstructors when an object is reclaimed by the garbage collector is called finalization. 46
  • 47. This reference class integers { int x; int y; public void setxy(int x,inty) { this.x=x; this.y=y; } … } 47
  • 48. Nesting of classes public class outer { …. // members of outer class public class inner { ….//members of inner class } } 48
  • 49. Constant members • Allows declaration of data fields of a class as constant. • public const int size=100; • Member size is initialized 100 during compilation , it cannot be changed later. • Any attempt done to assign a value to it, will result in compilation error. • Const members are implicitly static. • public static const int size=100; • Will produce compile time error, we cannot declare explicitly using static 49
  • 50. read-only members • Using readonly modifier, we can set the value of the member using a constructor method, cannot be modified later. • Declared as static fields or instance fields. class numbers { public readonly int m; public static readonly int n; public numbers(int x) { m=x; } static numbers() { n=100; } } 50
  • 51. properties • Accessor methods to access the data members • Mutator method  to set the value of the data members • Drawback: • We have to code accessor methods manually • Uses should remember that they have to use accessor methods to work with data members using system; class number { private int number; public int anumber; //property { get return number; set number=value; } } class propertytest { public void static main() { number n=new number(); n.anumber=100; int m=n.anumber; Console.WriteLine(“Number=”+m); } } 51
  • 52. indexers • They are location indicators • Used to access class objects just like accessing elements in array • Useful when class is container of other classes. • The indexer takes an index argument and looks like an array • The indexer is declared using name this. • Implemented using get and set accessors for the [] operator. public double this[int idx] { get { //return desired data } set {//set desired data } } 52
  • 53. Defining an interface • it contains one or more methods, properties, indexers, events but none of them are implemented in the interface itself. interface interface_name { member declarations; } eg. interface show { void display(); } 53
  • 54. Extending an interface Interface l1 { …. } interface l2 { …. } interface l3:l2,l1 { …. } 54 Interface name2:name1 { members of name2 } • Eg: interface addition { int add(intx,int y); } interface compute:addition { int sub(int x, int y); }
  • 55. Implementing interfaces class classname :interfacename { body of classname } • Here classname implements the interfacename class a:b,l1,l2 { … } • Where B is the base class and l1,l2 are the interfaces 55
  • 56. Abstract class and interfaces interface a { void method(); } abstract class b:a { .. public abstract void method(); } 56
  • 57. Delegates • Dictionary meaning of “Delegate” means a person acting for another person. • In C# it means a method acting for another method. • It is used to invoke a method that has been encapsulated into it at time of its creation. • Has four steps – Delegate declaration – Delegate methods definition – Delegate instantiation – Delegate invocation 57
  • 58. Delegate declaration • A delegate declaration defines a class using that System.Delagate base class. • Delegate methods are any functions whose signature matches the delegate signature exactly. • modifier delegate return-type delegate-name(parameters); • Delegate may be defined in the following places – Inside a class – Outside a class – As top level object in a namespace. • Delegates are implicitly sealed. 58
  • 59. Delegate methods • Methods whose references are encapsulated into a delegate instance are known as delegate methods or callable entities. • The signature and return type of the delegate methods must exactly match the signature and return type of the delegate. • They do not care – What type of object the method is being called against. – Whether the method is static or instance method. 59
  • 60. Delegate instantiation • New delegate-type(expression) • Delegate-type is the name of the delegate declared earlier whose object is to be created. • Expression must be method name or value of delegate type. delegate int productdelegate(int x,int y); class delegate { static int product (int a,int b) return (a*b); //delegate instantiation productdelegate p=new productdelegate(product); } 60
  • 61. Delegate invocation • delegate_object(parameter_list) • If the invocation return void, the result is nothing and therefore it cannot be used as an operand of any operator. • Eg. delegate(x,y); • If a method returns a value, then it can be used as an operand of any operator. • Eg. double result= delegate(2.56,45.73); 61
  • 62. Events • An event is a delegate type class member that is used by the object or class to provide a notification to other objects that an event has occurred. • The client object can act on an event by adding an event handler to the event. • modifier event type event-name; • Modifiers can be static,virtual,override,abstarct,sealed. • Typedelegate. • Eg: public event EventHandler click; • EventHandler is a delegate and click is an event. 62