VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
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
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
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.
• Typedelegate.
• Eg: public event EventHandler click;
• EventHandler is a delegate and click is an event.
62