Overview of C#. C# can be used to develop two categories of programs, namely, C# can be used to...

202
Overview of C# Overview of C#

Transcript of Overview of C#. C# can be used to develop two categories of programs, namely, C# can be used to...

  • Overview of C#

  • Overview of C#C# can be used to develop two categories of programs, namely,Executable application programs andComponent libraries

    C#ProgramsExecutableProgramsLibraryProgramsCLRApplication ProgramOutputCLROutput

  • ContinuedExecutable programs are written to carry out certain tasks and require the method Main in one of the classes.

    In contrast, component libraries dont require a Main declaration because they are not standalone applications.

  • Data Types

  • TokensThere are following five types of tokens:KeywordsIdentifiersLiteralsOperatorspunctuators

  • KeywordsKeywords are an essential part of a language definition. They implement specific features of the language. They are reserved, and cant be used as identifiers except when they are prefaced by the @ character.Example :abstractasbasecheckedconstdodoubleref

  • IdentifiersIdentifiers are programmer-designed tokens. They are used for naming classes, methods, variables, labels, namespaces, interfaces, etc.C# identifiers enforce the following rules:They can have alphabets, digits and underscore characters.They must not begin with a digit.Upper case letters and lower case letters are distinct.Keywords in standalone mode cant be used as identifiers.

  • LiteralsLiterals are the ways in which the values that are stored in variables are represented.

    C# literalsBoolean LiteralsCharacter LiteralsNumeric LiteralsIntegerRealSingle CharacterString Literals

  • ContinuedExamples :Integer literals : 123 -321 0 654321 0X2Real literals : 0.0083 -0.75 435.36 0.65e4Boolean literals : true falseSingle character literals : X 5 ;String literals : Hello 2001 5+3

  • ContinuedBackslash Character Literals

  • OperatorsOperators are symbols used in expressions to describe operations involving one or more operands.Examples :+-/*%

  • PunctuatorsPunctuators are symbols used for grouping and separating code. They define the shape and function of a program.Punctuators (also called as separators) in C# include:Parentheses ( )Braces { }Brackets [ ]Semicolon ;Colon :Comma ,Period .

  • C# Data TypesC# Data TypesValue TypesPointersReference TypesPredefinedtypesUserdefinedtypesPredefinedtypesUserdefinedtypes Integers Real no BooleansCharacters Enumerations Structures Classes Arrays Delegates Interfaces Objects Strings

  • Value TypesSimple TypesBooleanUnsignedSignedDecimalIntegralFloating PointCharacterNumeric

  • Integral TypeSigned IntegerslongsbyteintshortUnsigned Integersulongbyteuintushort

  • Size and Range of Signed Integer Types

  • Size and Range of Unsigned Integer Types

    TypeSize Minimum value Maximum valuebyteOne byte0255ushortTwo byte065,535uintFour byte04,294,697,295ulongEight byte018,446,744,073,709,551,615

  • Floating-Point TypesFloating-Pointdoublefloat

  • OthersDecimal Type : A high precision, 128-bit data type. Can store values in the range 1.0 X 10-28 to 7.9 X 1028 with 28 significant digits. To specify a number to be decimal type, we must append the character M (or m) to the value, like 123.45M, otherwise the value will be treated as double.Character Type : The char type assumes a size of two bytes but, in fact it can hold only a single character.Boolean Type : Used to test a particular condition during the execution of a program. It can take the two values : true or false (in contrast to C and C++, we cant use zero for false and non-zero for true).

  • Accessibility

  • Access ModifiersAccess modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the four access modifiers: publicprotectedinternalprivateThe following five accessibility levels can be specified using the access modifiers:public: Access is not restricted.protected: Access is limited to the containing class or types derived from the containing class.Internal: Access is limited to the current assembly.protected internal: Access is limited to the current assembly or types derived from the containing class.private: Access is limited to the containing type.

  • Variables & Constants

  • Variables - DeclarationSyntax : type var1, var2, ., varN;Examples : int count;float x, y;double pi;ulong n;

  • Variables - InitializationSyntax : variableName = value;Variables must have Value before being used.Examples :i = 0;y = x;String assignment expression : x = y = z;At the time of declaration : int val = 100; char y = x; bool test = true; ulong ul = 123UL; decimal d = 1.23M;

  • Default ValuesFollowing are automatically initialized to their default values:Static variablesInstance variablesArray elements

  • ConstantsThe variables whose value dont change during the execution of a program can be made unmodifiable by using the const keyword while initializing them.Examples :const int rows = 10;const int m; //Illegal as constants must be m = 10; //Declared and initialized simultaneouslyNon-constant values cant be used : int m = 10; //Non-constant value const int n = m * 5; // Error

  • Types Of VariablesC# defines several categories of variables as :Static variablesInstance variablesArray elementsValue parametersReference parametersOutput parametersLocal variables

  • ContinuedExample :Class ABC{static int m;int n;void fun (int x, ref int y,out int z, int [] a) {int j = 10;}}This code contains the following variables:Static variable mInstance variable nArray elements a[0]Value parameter xReference parameter yOutput parameter zLocal variable j

  • C# StatementsA statement is an executable combination of tokens ending with a semicolon.C# implements several types of statements including :

  • Sample Program

  • A Simple C# ProgramClass SampleOne{public static void Main(){System.Console.WriteLine (Hello)}}

  • Class DeclarationThe first line : class sampleOne declares a class, which is an object-oriented construct. C# is a true object-oriented language and therefore, everything must be placed inside a class. class a keyword and declares that a new class definition follows. SampleOne is a C# identifier that specifies the name of the class to be defined.

  • The BracesC# is a block structured language, meaning code blocks are always enclosed by braces{ and }.Therefore every C# program begins with an opening brace { and ends with a corresponding closing brace }.Note that there is no semicolon after the closing brace.

  • The Main MethodThe third line : public static void Main() defines a method named Main. Every C# program must include the Main() method in one of the classes. This is the starting point for executing the program. A C# application can have any number of classes but only one class can have the Main() method to initiate the execution.

  • ContinuedThe meaning and purpose of other keywords are:public : The keyword public is an access modifier that tells the C# compiler that the Main method is accessible by anyone.static : The keyword static declares that the Main method is a global one and can be called without creating an instance of the class. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created.void : The keyword void is a type modifier that states that the Main method does not return any value (but simply prints some text to the screen).

  • The Output LineThe only executable statement in the program is System.Console.WriteLine(Hello). The WriteLine Method is a static method of the Console class, which is located in the namespace System. This line prints the string Hello to the screen. The method WriteLine always appends a new-line character to the end of the string. This means any subsequent output will start on a new line.Note the semicolon at the end of the statement. Every C# statement must end with a semicolon.

  • Executing The Program

  • Executing The ProgramAfter creating the program (source code), save it with .cs file extension in a folder of your system. Example sampleone.csFor compiling the program, go to the folder where you have stored the file sampleone.cs and then type the following command : csc sampleone.csThe C# compiler (CSC) compile your code and create an executable file (IL code) by name : sampleone.exe in the same directory (if the code is error-free). If there are any errors the compiler will produce appropriate error message. Errors should be corrected and the program should be compiled again.

  • ContinuedFor executing the program, simply type the name of the executable file at the command prompt. That is : sampleoneNote that no file extension is used. This will display the output : Hello on the screen.C# CodeIL CodeNative Machine CodeOutput(.cs file)Execution(.exe file)C# CompilationJIT Compilation

  • Namespace System

  • NamespaceConsider the output statement of the previous sample again : System.Console.WriteLine();In this, we noted that System is the namespace (scope) in which the Console class is located. A class in a namespace can be accessed using the dot operator. Namespaces are always the way C# segregates the .Net library classes into reasonable groupings.C# supports a feature known as using directive that can be used to import the namespace System into the program. Once a namespace is imported, we can use the elements of that namespace without using the namespace as prefix.

  • A Program Using Namespace & Comments/*This program uses namespace and comment lines*/Using System; //System is a namespaceClass SampleTwo{//Main method beginspublic static void Main(){Console.WriteLine (Hello)}//Main method ends}

  • ContinuedNote that the first statemnet in the program is : using System; This tells the compiler to look in the System library for unresolved class names. Note that we have not used the System prefix to the Console class in the output lineWhen the compiler parses the Console.writeLine method, it will understand that the method is undefined. However, it will then search through the namespaces specified in using directives and, upon finding the method in the System namespace, will compile the code without any complaint.

  • Adding CommentsC# permits two types of comments, namely,Single-line comments : using System; //single line commentMultiline comments : /* This is an example of Multiline comments in C# language */

  • Main() Variation

  • Main Returning A Value//Main returning a valueUsing System;Class SampleThree{public static int Main(){Console.WriteLine (Hello);return 0; //Return statement}}The value returned serves as the programs termination status code. The purpose of this code is to allow communication of success or failure to the execution environment.

  • Main With A ClassClass TestClass //class definition{public void fun( ){System.console.WriteLine (Hello);}}Class SampleSeven{public static void Main(){TestClass test = new TestClass( ); //creating test objecttest.fun( ); //calling fun( ) function}}

  • Using Aliases For ClassesSyntax : using alias-name = class-name;Example :using A = System.Console; //A is alias for System.ConsoleClass SampleFour{public static void mMain(){A.WriteLine (Hello);}}

  • Passing String Objects To WriteLine MethodUsing System;Class SampleFive{public static void Main(){string name = C sharp;Console.WriteLine (name);}}

  • Command Line Arguments

  • Command Line ArgumentsCommand Line Arguments are parameters supplied to the Main method at the time of invoking it foe execution.Example :Using System;Class SampleSix{public static void Main (string [ ] args){Console.WriteLine (welcome to);Console.WriteLine ( +args[0]);Console.WriteLine ( +args[1]);}}Main is declared with a parameter args. The parameter args is declared as an array of string. Any argument provided in the command line (at the time of its execution) are passed on to args as its elements.We can access the array elements by using a subscript like args[0], args[1] and so on.

  • ContinuedFor example consider the command line : SampleSix C SharpThis command line contains two arguments which are assigned to the array args as follows:C args[0]Sharp args[1]If we execute the above program, the output will be : welcome to C Sharp

  • ContinuedThe new output method : Console.Write does not cause a line break and therefore the next output line is printed on the same line.

  • Programming

  • Looping StatementsSame as C + + while (count > 0) process_list (count--);

    do process_list( ++count ); while (count < 10);

    for (int i=1; i

  • Decision Statementsif (count >= 10) { dostuff(); domorestuff(); }else ...

    switch (choice){ case 'Y': //must be empty case 'y': do_yes_stuff(); break; default:...

    Almost just like C + +

  • Methods

  • Declaring MethodsSyntax : Modifiers type methodname (formal-parameter list) {method_body }It has five parts:Name of the method (methodname)Type of value the method returns (type)List of parameters (formal-parameter list)Body of the methodMethod modifiers (modifier)

  • Sample Method int Product ( int x, int y ) {int m = x * y; // operation. m is a local variablereturn (m); }

    The return statement must be omitted if the method does not return value.Example : void Display ( int x ) {Console.WriteLine (x); }

  • Method ModifiersThe modifiers specify keywords that decide tha nature of accessibility and the mode of application of the method. A method can take one or more of the following modifiers :

  • The MainMethodC# program start execution at a method named Main().This method must be the static method of a class and must have either int or void as return typeThe modifier public is used as this method must be called from outside the program.The Main can also have parameters which may receive values from the command line at the time of execution.Examples : public static int Main() public static void Main() public static int Main(string [ ] args) public static void Main(string [ ] args)

  • Invoking MethodsSyntax : objectname.methodname( actual-parameter list );Example : using System; class Method //class containing the method {//Define the Cube method int Cube ( int x ){return ( x * x * x );} }

  • Continued //Client class to invoke the Cube method class MethodTest {public static void Main(){ //Create object for invoking the Cube method Method M = new Method ( );

    //Invoke the Cube method int y = M.Cube (5); //Method Call

    //Write the result Console.WriteLine ( y );} } Output : 25

  • Calling a Static MethodStatic methods are called without using any object.Example : using System; class StaticMethod{public static void Main(){double y = Square (2.5 F); //Method callConsole.WriteLine ( y );}static double Square ( float x ) //Method definition{return ( x * x );}}

  • Method ParametersC# employs four kinds of parameters :Value parametersReference parametersOutput parametersParameter arrays

  • Pass By ValueBy default, method parameters are passed by value. That is, a parameter declared with no modifier is passed by value and is called a value parameter.Example :using System;class PassByValue{static void Change ( int m ){m = m + 10; //value of m is changedConsole.WriteLine (m = + m);

    }

  • Continuedpublic static void Main( ){int x = 100;Change (x);Console.WriteLine (x = + x);}}Output : m = 110 x = 100When the method change( ) is invoked, the value of x is assigned to m and a new location for m is created in the memory. Therefore, any change in m dont affect the value stored in location x.

  • Pass By ReferenceA parameter declared with the ref modifier is a reference parameter as : void Modify ( ref int x )A reference parameter does not create a new storage location. Instead it represents the same storage location as the actual parameters used in the method invocation.When a formal parameter is declared as ref, the corresponding argument in the method invocation must also be declared as ref.

  • ContinuedExample :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;int n = 200;Console.WriteLine (Before Swapping);Console.WriteLine (m = + m);Console.WriteLine (n = + n);

  • ContinuedSwap ( ref m, ref n);Console.WriteLine (After Swapping);Console.WriteLine (m = + m);Console.WriteLine (n = + n);}}Output :Before swappingm = 100n = 200After swappingm = 200n = 100

  • The Output ParametersOutput parameters are used to pass result back to the calling method. Declared with an out keyword. It doesnt create a new storage but becomes an alias to the parameter in the calling method.Example :using System;class Output{static void Square ( int x, out int y ){y = x * x;}

  • Continuedpublic static void Main( ){int m; //need not be initializedSquare( 10, out m );Console.WrieLine (m = + m);}}Output : m = 100

  • Method OverloadingC# allows us to create more than one method with the same name, but with different parameter lists and different dfinitions. This is called as method overloading.Example ://Method definitionsint add ( int a, int b ){} //Method1int add ( int a, int b, int c ){} //Method2double add ( float a, float b ){} //Method3double add ( int a, float b ){} //Method4double add ( float a, int b ){} //Method5

    //Method callsint m = add (5, 10); //calls Method1int n = add (5, 10, 20); //calls Method2double x = add (15, 2.0F); //calls Method3double y = add (1.0F, 2.0F); //calls Method4double z = add (1.0F, 2); //calls Method5

  • ContinuedExample :using System;class Overloading{public ststic void Main( ){Console.WriteLine (volume (10));Console.WriteLine (volume (2.0F, 8));Console.WriteLine (volume (100L, 75, 15));}static int volume ( int x ) //cube{return ( x * x * x );}

  • Continuedstatic double volume ( float r, int h ) //cylinder{return ( 3.14519 * r * r * h );}static long volume ( long l, int b, int h ) //box{return ( l * b * h );}}Output :1000157.2595112500

  • Arrays & Strings

  • ArrayCreating an array :Declaring the arrayCreating memory locationsPutting values into the memory locations

    Declaration : type[ ] arrayname;Examples :int[ ] counter; //declare int array reference float[ ] marks; //declare float array referenceint[ ] x,y; //declare two int array reference

    Creation : arrayname = new type[size];Examples :number = new int[5]; //create a 5 element int arrayaverage = new float[10]; //create a 10 element float array

  • ContinuedInitialization : arrayname[subscript] = value;Examples :number[0] = 35;number[1] = 26;number[4] = 14;

    Arrays can be initialized automatically in the same way as ordinary variables when they are declared as : type [ ] arrayname = {list of values}; Examples :int [ ] number = {35, 26, 20, 57, 14};

  • ContinuedIt is possible to assign an array object to another as : int[ ] a = {1,2,3};int[ ] b;b= a;We can access the length of the array a using a.Length. Example : int aSize = a.Length;

  • Two-Dimensional ArrayCreation :int[ , ] arr1;arr2 = new int[3, 4];int[ , ] arr3 = new int[3,4];int[ , ] table = {{0,0,0},{1,1,1}};

  • Variable-Size ArrayC# treats multidimensional arrays as array of arrays. It is possible to declare a two-dimensional array as follows :int[ ][ ] x = new int[3][ ]; //three rows arrayx[0] = new int[2]; //first row has two elementsx[1] = new int[4]; //second row has four elementsx[2] = new int[3]; //third row has three elements

  • StringsC# supports two types of strings : mutable and immutable. It also supports a feature known as regular expression that can be used for complex string manipulations and pattern matching.

    C# StringsImmutableStringsRegularExpressionsMutableStringsSystem.StringClassStringBuilderClass

  • ContinuedCreating strings :Assigning string literals :string s1; //declaring a string objects1 = abc; //assigning string literalstring s1 = abc; //declaring an assigningCopying from one object to anotherstring s2 = s1; //assigningstring s2 = string.Copy (s1); //copyingConcatenating two objectsstring s3 = s1 + s2; //s1 and s2 already existstring s3 = string.Concat(s1, s2);Reading from the keyboardstring s = Console.ReadLine( );Using ToString methodint number = 123;string numStr = number.ToString( );

  • String MethodsInsert( ) : Returns a new string with a substring inserted at a specified location.string s1 = s1.Insert(3, r);Compare( ) : Compares two string.1)int n = string.Compare(s1, s2);returns zero if s1 is equal to s2returns a positive integer(1) if s1 is greater than s2returns a negitive integer(-1) if s1 is less than s22)int n = string.Compare(s1, s2, true); //case is ignoredEquals( ) : Determines two strings are equal.bool b1 = s2.Equals(s1);bool b2 = string.Equals(s2, s1);returns true if s1 is equal to s2 and false otherwise

  • ContinuedSubstring( ) : Extracts a substring starting from nth position.1)String s1 = New York;string s2 = s1.Substring(5); //s2 = York2)String s1 = New York;string s2 = s1.Substring(0, 3); //s2 = NewThe == operator : Tests the equality.bool b3 = (s1 == s2); //b3 is true if they are equal

  • Object Oriented Concepts

  • ClassesDefining a class : class classname{[ variables declaration; ][ methods declaration; ]}Class MembersInstanceMembersStaticMembersDataMembersFunctionMembersConstantsFieldsEventsMethodPropertiesDestructorsConstructorsIndexers

  • ContinuedAdding variables :class Rectangle{int length; //instance variableint width; //instance variable}Adding Methods :class Rectangle{int length, width;public void GetData( int x, int y ){length = x;width = y;}public int RectArea( ){int area = length * width; //area is local variablereturn(area);}}

  • ObjectsCreation :Rectangle rect1; //declarerect1 = new Rectangle( ); //instantiateAccessing class members :rect1.length = 15;rect1.width = 10;Reactangle rect3 = new Rectangle( ); rect3.GetData(20, 30);int area3 = rect3.RectArea( );

  • ConstructorConstructor is a special type of method that enables an object to initialize itself when it is created. They have the same name as the class itself and they dont specify a return type, not even void as they dont return any value.Example :class Rectangle{int length, width;public Rectangle( int x, int y ) //Constructor method{length = x;width = y;}public int RectArea( ){return(length * width );}}

  • Overloaded Constructorclass Room{public double length, breadth;public Room( double x, double y ) //constructor1{length = x;breadth = y;}public Room( double x ) //constructor2{length = breadth = x;}public RoomArea( ){return( length * breadth );}}

  • Copy ConstructerA copy constructor creates an object by copying variables from another object.Example :public Item( Item i ){code = i.code;price = i.price;}Invoking : Item i2 = new Item( i1 );

  • DestructorsIt is a method called when an object is no more required. The name of destructor is same as class name and is preceded by a tilde (~). Like constructor, it has no return type.Example :Class Fun{~ Fun( ) //No arguments{..}}

  • InheritanceABDCBASingle InheritanceMultiple InheritanceMultilevel InheritanceHierarchical InheritanceABCCBA

  • ContinuedDefining a subclass :class subclass-name : baseclass-name{variables declarations;methods declarations;}Example :class Cylinder : Circle{//Add additional fields//and methods here}

  • Simple Inheritanceusing System;class Item{public void Company ( ) //base class{Console.WriteLine( Item Code = XXX );}}class Fan : Item //derived class{public void Model( ){ Console.WriteLine( Fan Model : Classic );}}

  • Continuedclass SampleInheritance{public static void Main(){Item i = new Item( );Fan f = new Fan( );i.Company( );f.Company( );f.Model( );}}Output :Item Code = XXXItem Code = XXXFan Model = Classic

  • Visibility of Class Members

  • Accessibility Domain of Class Members

  • Overriding MethodsThere may be occasions when we want an object to respond to the same method but behave differently when the method is called. That means, we should override the method defined in the superclass.This is possible by defining a method in the subclass that has the same name, same arguments, and same return type as method in the superclass.Thus when that method is called, the method defined in the subclass is invoked and executed instead of one in the superclass, provided that :The method in baseclass is specified as virtualImplement the method in subclass using the keyword override

  • Overriding Methods Exampleusing System;class Super //baseclass{protected int x;public Super ( int x ){this.x = x;}public virtual void Display ( ) //method defined with virtual{Console.WriteLine(Super x = + x);}}

  • Continuedclass Sub : Super //derivedclass{int y;public Sub ( int x, int y ){this.y = y;}public override void Display ( ) //method defined again with override{Console.WriteLine(Super x = + x);Console.WriteLine(Sub y = + y);}}

  • Continuedclass OverrideTest{public static void Main( ){Sub s1 = new Sub (100, 200);s1.Display( );}}Output : Super x = 100Sub y = 200Base method can be called using the base reference as : base.Display( );

  • Sealed ClassesA class that cant be subclassed, i.e. , cant be used as baseclass for derivation is called as a sealed class. It is done using the modifier sealed.Example :1) sealed class Aclass{.}2) Sealed class Bclass : Someclass{.}

  • PolymorphismPolymorphism OperationPolymorphismUsingVirtual MethodsUsingOverloaded MethodsInclusionPolymorphism

  • Operation Polymorphismusing System;class Dog{}class Cat{}class Operation{static void Call (Dog d){Console.WriteLine(Dog is called);}static void Call (Dog d){Console.WriteLine(Cat is called);}}

  • Continuedpublic static void Main( ){Dog d = new Dog( );Cat c = new Cat( );Call(d); //invoking Call( )Call(c); //again invoking Call( )}}Output :Dog is calledCat is called

  • Inclusion Polymorphismusing System;class Maruti{public virtual void Display ( ) //virtual method{ Console.WriteLine(Maruti Car);}}

    class Esteem : Maruti{public override void Display ( ){ Console.WriteLine(Maruti Esteem);}}

  • Continuedclass Zen : Maruti{public override void Display ( ){ Console.WriteLine(Maruti Zen);}}class inclusion{public ststic void Main( ){Maruti m = new Maruti( );

  • Continuedm = new Esteem( ); //upcastingm.Display( );m = new Zen( ); //upcastingm.Display( );}}Output :Maruti : EsteemMaruti : Zen

  • Abstract ClassesThe abstract is a modifier and when used to declare a class indicates that the class cant be instantiated. Only its derived class, that are not marked abstract can be instantiated.Example :abstract class Base{..}class Derived : Base{..}..Base b; //ERROR!!Derived d; //OK

  • Abstract MethodsAn abstract method is implicitly a virtual method and doesnt provide any implementation. Therefore, an abstract method doesnt have method body.Example :public abstract void Draw(int x, int y );Note that the method body simply consists of a semicolon.

  • Interfaces Multiple Inheritencean interface is a kind of class with some differences, like, all the members of an interface are implicitly public and abstract.Although a C# class cant be a subclass of more than one superclass, it cam implement more than one interface.

  • Defining an InterfaceSyntax :interfcae InterFaceName{Member Declarations;}Example :interface Example{void Display( ); //Note semicolon here

  • Extending an InterfaceSyntax :interface name2 : name1{Members of name2;}Example :interface Addition{int Add(int x, int y);}interface Compute : Addition{int Sub (int x, int y)}

  • Multiple Inheritenceinterface A{..}interface B{..}interface C : A, B //Multiple Inheritence{..}

  • Operator Overloading

  • OverviewC# supports operator overloading which means that C# operators can be defined to work with the user-defined data types in much the same way as the built-in types.

  • Overloadable Operators

  • Operators That Cant Be overloaded

  • Defining Operator Overloading public static retval operator op (arglist){Method body //task defined}They must be defined as public and static.The retval (return value) type is the type that we get when we use this operator.The arglist is the list of arguments passed. The number of arguments will be one for unary and two for binary operators.In the case of unary operators, the argument must be the same type as that of the enclosing class or struct.In the case of binary operators, the first argument must be the same type as that of the enclosing class or struct and the second may be of any type.

  • Overloading Unary Minususing System;class Space{int x, y, z;public Space (int a, int b, int c){x = a;y = b;z = c;}public void Display ( ){Console.Write( = x);Console.Write( = y);Console.Write( = z);

  • ContinuedConsole.WriteLine( );}public static Space operator (Space s){s.x = -s.x;s.y = -s.y;s.z = -s.z;}}class SpaseTest{public static void Main( ){Space s = new Space(10, -20, 30);Console.Write( s : );s.Display( );-s; //activates operator ( ) methodConsole.Write( s : );s.Display( );}}

  • Overloading Binary Operatorusing System;class Complex{double x; //real partdouble y; //imaginary partpublic Complex{}public Complex ( double real, double img ){x = real;y = img;}

  • Continuedpublic static Complex operator + (Complex c1, Complex c2){Complex c3 = new Complex( );c3.x = c1.x + c2.x;c3.y = c1.y + c2.y;return(c3);}public void Display( ){Console.Write(x);Console.WriteLine( + j+ x);Console.WriteLine( );}}class ComplexTest{public static void Main( ){Complex a, b, c;a = new Complex (2.5, 3.5);b = new Complex (1.6, 2.7);c = a + b;

  • ContinuedConsole.Write( a = );a.Display( );Console.Write( b = );b.Display( );Console.Write( c = );c.Display( );}}Output :a = 2.5 + j3.5b = 1.6 + j2.7c = 4.1 + j6.2

  • Delegates & Events

  • DelegatesDelegate means a method acting for another method.A delegate in C# is a class type object and is used to invoke a method that has been encapsulated into it at the time of its creation.Creating and using delegates include four steps:Delegate declarationDelegate methods definitionDelegate instantiationDelegate invocation

  • DeclarationSyntax : modifier delegate return-type delegate-name (parameters);Examples :delegate void SimpleDelegate( );delegate int MathOperation(int x, int y );public delegate int Compare (object o1, object o2 );Delegate may take any of the following identifier :new : only permitted on delegates declared within another type.publicprotectedinternalprivate

  • Delegate MethodsThe methods whose reference are encapsulated into a delegate instance are known as delegate methods or callable entities.The signature and return type of delegate methods must exactly match the signature and return type of delegate.Example :delegate string GetString( ) can be made to refer to the method ToString() using an int object N as follows :..int N = 100;GetString s1 = new GetString(N.ToString);

  • Delegate InstantiationA delegate-creation-expression is used to create a new instance of a delegate : new delegate-type (expression)Example :class A{//delegate methodpublic void DisplayA( ) //instance method{Console.WriteLine(Display A);}}..//delegate instanceA a = new A( ); //create object aDisplayDelegate d1 = new DisplayDelegate(a.DisplayA);

  • Delegate InvocationWhen a delegate is invoked, it in turn invokes the method whose reference has been encapsulated into the delegate, (only if there signatures match). Invocation takes the following form : delegate-object (parameters list).Examples :delegate(x, y); //void delegatedouble result = delegate2(2.56, 45.73);

  • Creating and Implementing a Delegateusing System;//delegate declarationdelegate int ArithOp(int x, int y);class MathOperation{//delegate method definitionpublic static int Add(int a, int b){return (a + b);}public static int Sub(int a, int b){return(a - b);}}

  • Continuedclass DelegateTest{public static void Main( ){//delegate instancesArithOp operation1 = new ArithOp (MathOperation.Add);ArithOp operation2 = new ArithOp (MathOperation.Sub);

    //invoking delegateint result1 = operation1(200, 100);int result2 = operation2(200, 100);Console.WriteLine(Result1 = + result1);Console.WriteLine(Result2 = + result2);}}Output :Result1 = 300Result2 = 100

  • Multicast DelegatesMulticast delegates, also known as combinable delegates, can hold and invoke multiple methods.They must satisfy the following conditions :The return type of the delegate must be void.None of the parameters of the delegate type can be declared as output parameters, using out keyword.

  • Implementing Multicast Delegatesusing System;delegate void MDelegate( );class DM{static public void Display( ){Console.writeLine(New Delhi);}static public void Print( ){Console.writeLine(New York);}}class MTest{public static void Main( ){

  • ContinuedMDelegate m1 = new MDelegate(DM.Display);MDelegate m2 = new MDelegate(DM.Print);MDelegate m3 = m1 + m2;MDelegate m4 = m2 + m1;MDelegate m5 = m3 - m2;

    //invoking delegatesm3( );m4( );m5( );}}Output :New DelhiNew York New YorkNew DelhiNew Delhi

  • EventsAn 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.Declaration : modifire event type event-name;Examples :public event EventHandler Click;public event RateChange Rate;Here EventHandler and RateChange are delegates and Click and Rate are events.

  • Implementing an Eventusing System;//delegate declaration firstpublic delegate void Edelegate(string str);class EventClass{//declaration of eventpublic event Edelagate Status;public void TriggerEvent(){if (Status != null)Status(Event Triggered);}}

  • Continuedclass EventTest{public static void Main( ){EventClass ec = new EventClass( );EventTest et = new EventTest( );ec.Status += new Edelegate(et.EventCatch);ec.TriggerEvent( );}public void EventCatch(string str){Console.WriteLine(str);}}Output :Event Triggered

  • ArrayList & Indexer

  • ArrayListStores a dynamically sized array of objects.Supports operations such as sorting, removing and enumerating its contents.Count property return the no of objects in the arraylist.ArrayList cities=new ArrayList(30);cities.add(Bombay);cities.add(Mumbai);

  • IndexersIndexers are location indicators and are used to access class objects, just like accesing elements in an array.The indexer is declared using the name this and implemented through get and set accessors for the [ ] operator.Example :public double this[ int idx ]{get{//Return desired data}set{//Set desired data}}

  • Implementation of an Indexerusing system;using System.Collections;class List{ArrayList array = new ArrayList( );public object this[int index]{get{if (index < 0 || index >= ayyay.Count) return null;else

    array[index] = value;}set{array[index] = value;}}}

  • Continuedclass Indexer Test{public static void Main( ){List list = new List( );list[0] = 123;list[1] = abc;list[2] = xyz;for (int i = 0; i < list.Count; i++)Console.WriteLine(list[i]);}}

  • ThreadingWhat is a thread?Every application runs with at least one thread. So what is a thread? A thread is nothing more than a process. My guess is that the word thread comes from the Greek mythology of supernatural Muses weaving threads on a loom, where each thread represents a path in time of someone's life. If you mess with that thread, thenyou disturb the fabric of life or change the process of life. On the computer , a thread is a process moving through time. The process performs sets of sequential steps, each step executing a line of code. Because the steps are sequential, each step takes a given amount of time. The time it takes to complete a series of steps is the sum of the time it takes to perform each programming step.What are multithreaded applications?For a long time, most programming applications (except for embedded system programs) were single-threaded. That means there was only one thread in the entire application. You could never do computation A until completing computation B. A program starts at step 1 and continues sequentially (step 2, step 3, step 4) until it hits the final step (call it step 10). A multithreaded application allows you to run several threads, each thread running in its own process. So theoretically you can run step 1 in one thread and at the same time run step 2 in another thread. At the same time you could run step 3 in its own thread, and even step 4 in its own thread. Hence step 1, step 2, step 3, and step 4 would run concurrently. Theoretically, if all four steps took about the same time, you could finish your program in a quarter of the time it takes to run a single thread (assuming you had a 4 processor machine). So why isn't every program multithreaded? Because along with speed, you face complexity. Imagine if step 1 somehow depends on the information in step 2. The program might not run correctly if step 1 finishes calculating before step 2 or visa versa.

  • ContinueWhen to ThreadMultiple threading is most often used in situations where you want programs to run more efficiently. For example, let's say your Window Form program contains a method (call it method_A) inside it that takes more than a second to run and needs to run repetitively. Well, if the entire program ran in a single thread, you would notice times when button presses didn't work correctly, or your typing was a bit sluggish. If method_A was computationally intensive enough, you might even notice certain parts of your Window Form not working at all. This unacceptable program behavior is a sure sign that you need multithreading in your program. Another common scenario where you would need threading is in a messaging system. If you have numerous messages being sent into your application, you need to capture them at the same time your main processing program is running and distribute them appropriately. You can't efficiently capture a series of messages at the same time you are doing any heavy processing, because otherwise you may miss messages. Multiple threading can also be used in an assembly line fashion where several processes run simultaneously. For example once process collects data in a thread, one process filters the data, and one process matches the data against a database. Each of these scenarios are common uses for multithreading and will significantly improve performance of similar applications running in a single thread.

  • Continue

  • Exampleusing System;using System.Threading;

    public class Worker{ // This method will be called when the thread is started. public void DoWork() { while (!_shouldStop) { Console.WriteLine("worker thread: working..."); } Console.WriteLine("worker thread: terminating gracefully."); } public void RequestStop() { _shouldStop = true; } // Volatile is used as hint to the compiler that this data // member will be accessed by multiple threads. private volatile bool _shouldStop;}

  • Continuepublic class WorkerThreadExample{ static void Main() { // Create the thread object. This does not start the thread. Worker workerObject = new Worker(); Thread workerThread = new Thread(workerObject.DoWork);

    // Start the worker thread. workerThread.Start(); Console.WriteLine("main thread: Starting worker thread...");

    // Loop until worker thread activates. while (!workerThread.IsAlive);

    // Put the main thread to sleep for 1 millisecond to // allow the worker thread to do some work: Thread.Sleep(1);

    // Request that the worker thread stop itself: workerObject.RequestStop();

    // Use the Join method to block the current thread // until the object's thread terminates. workerThread.Join(); Console.WriteLine("main thread: Worker thread has terminated."); }}

  • MultiThreding// shared memory variable between the two threads // used to indicate which thread we are in private string _threadOutput = ""; /// Thread 1: Loop continuously, /// Thread 1: Displays that we are in thread 1 void DisplayThread1() { while (_stopThreads == false) { Console.WriteLine("Display Thread 1"); // Assign the shared memory to a message about thread #1 _threadOutput = "Hello Thread1"; Thread.Sleep(1000); // simulate a lot of processing // tell the user what thread we are in thread #1, and display shared memory Console.WriteLine("Thread 1 Output --> {0}", _threadOutput); } } /// /// Thread 2: Loop continuously, /// Thread 2: Displays that we are in thread 2 /// void DisplayThread2() { while (_stopThreads == false) { Console.WriteLine("Display Thread 2"); // Assign the shared memory to a message about thread #2 _threadOutput = "Hello Thread2"; Thread.Sleep(1000); // simulate a lot of processing // tell the user we are in thread #2 Console.WriteLine("Thread 2 Output --> {0}", _threadOutput); } }

  • Continue Class1() { // construct two threads for our demonstration; Thread thread1 = new Thread(new ThreadStart(DisplayThread1)); Thread thread2 = new Thread(new ThreadStart(DisplayThread2)); // start them thread1.Start(); thread2.Start(); } :

  • Output

  • NetworkingAllows computers and other networked devices to talk to each otherHow can we tell what the packet we just received means?Interactions between applications on different machines are governed by protocolsProtocols dictate the format and sequence of the information exchange

  • Names and AddressA network address identifies a specific computer on the networkSeveral kinds of addresses exist: MAC address (for LANs), IP address (for the Internet), etc.Domain or DNS names are used for convenience, so we dont have to remember numerical addresses

  • PortsPorts are numbers that represent an end-point for communicationPorts are logical, not physical, entitiesAll packets arrive to the same physical interface, and are then differentiated based on the port number (and other contents of the packet header)Usually, distinct ports are used for communication via different protocolsE.g., port 80 is for HTTP.

  • SocketsStandard API for sending and receiving data across computer networksCan also be used for interprocess communication on a single machineIntroduced by BSD operating systems in 1983POSIX incorporated 4.3BSD sockets in 2001Some socket calls (socket, recv, send, close) parallel Kernel file I/O calls (open, read, write, close), and operate similarly.

  • Using Sockets in C# #include #include #include #include On csil-core: gcc o test test.cOn some systems, e.g., Solaris: gcc o test test.c lsocket -lnsl

  • TCP Client/Server Example Run the provided test-server and test-client executables in two separate windows.test-client sends the string Hello World! to IP address 127.0.0.1 port 10000test-server listens on port 10000 and prints out any text received

  • Generic TCP Client & Server Script

  • Socketint socket(int domain, int type, int protocol);Creates a communication endpoint Local action only; no communication takes placeParameters domain: AF_INET (IPv4) type: SOCK_STREAM (TCP) or SOCK_DGRAM (UDP) protocol: 0 (socket chooses the correct protocol based on type)Returns a nonnegative integer corresponding to a socket file descriptor if successful, -1 with errno set if unsuccessful

  • Connectint connect(int socket, const struct sockaddr *address, socklen_t address_len);Establishes a link to a well-known port of the remote server Initiates the TCP 3-way handshake (exchange packets with the remote machine to mutually set up a connection)Returns 0 if successful, -1 with errno set if unsuccessful struct sockaddr_in sa; connect(sock, (struct sockaddr *)&sa, sizeof(sa));

  • struct sockaddr / sockaddr_in struct sockaddr_in used for address sa_family_t sin_family;/* AF_INET */ in_port_t sinport;/* port number */ struct in_addrsin_addr;/* IP address */For example: sa.sin_family = AF_INET; sa.sin_port = htons(80); sa.sin_addr.s_addr = inet_addr(127.0.0.1);

  • send and sendto int send(int socket, const void *msg, int len, int flags);int sendto(int socket, const void *msg, int len, int flags, const struct sockaddr *to, socklet_t tolen);sends data pointed by msgsendto is used for unconnected datagram sockets. If used in connection-mode, last two parameters are ignored.Returns the number of bytes actually sent out if successful, -1 with errno set if unsuccessful.For our examples, use 0 for flags.

  • Close and Shutdownint close(int socket);int shutdown(int socket, int how);close Prevents any more reads and writes same function as for file systemsshutdown provides a little more control how 0 Further receives are disallowed 1 Further sends are disallowed 2 same as closeReturns 0 if successful, -1 with errno set if unsuccessful

  • What about the server?First call socket() as with the client. Then

  • Bindint bind(int socket, const struct sockaddr *address, socklen_t address_len);Associates the socket with a port on your local machine Local action; no communication takes place yetReturns 0 if successful, -1 with errno set if unsuccessful.Use struct sockaddr_in, like in the connect() call.

  • Caution!Exiting or crashing after calling bind() but before close() will cause problems!Cannot bind() the same port for a few minutes Prevent a different application from accidentally receiving our connectionsUnless SO_REUSEADDR option is used with setsockopt() Permits the server to be restarted immediately

  • setsockopt int sock;int true = 1;if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) exit(EXIT_FAILURE);if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&true, sizeof(true)) == -1) { error = errno; while ((close(sock) == -1) && (errno == EINTR)); errno = error; exit(EXIT_FAILURE);}

  • Listenint listen(int socket, int backlog); Puts the socket into the passive state to accept incoming requests.Internally, it causes the network infrastructure to allocate queues to hold pending requests. backlog: number of connections allowed on the incoming queuebind() should have been called beforehandReturns 0 if successful, -1 with errno set if unsuccessful.

  • Acceptint accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len); Accepts the pending connection requests into the incoming queue*address is used to return the information about the client making the connection. sin_addr.s_addr holds the Internet addresslisten() should have been called beforehandReturns nonnegative file descriptor corresponding to the accepted socket if successful, -1 with errno set if unsuccessful

  • recv and recvfrom int recv(int socket, void *buf, int len, int flags); int recvfrom(int socket, void *buf, int len, int flags, const struct sockaddr *from, socklet_t fromlen); receives data into the buffer bufrecvfrom is used for unconnected datagram sockets. If used in connection-mode, last two parameters are ignored.Returns the number of bytes actually read if successful, -1 with errno set if unsuccessful.For our examples, use 0 for flags.

  • Exercise: socket code Insert the appropriate calls into the appropriate places in socket.c and server.c.Compile your client and server implementations.Try testing: client with test-server test-client with server client with serverAll should work.

  • Exception HandlingA try block is used by C# programmers to partition code that may be affected by an exception, and catch blocks are used to handle any resulting exceptions.A finally block can be used to execute code regardless of whether an exception is thrown--which is sometimes necessary, as code following a try/catch construct will not be executed if an exception is thrown.A try block must be used with either a catch or a finally block, and can include multiple catch blocks.

  • Syntax: try-catchtry{ // Code to try here.}catch (System.Exception ex){ // Code to handle exception here.}**A try statement without a catch or finally block will result in a compiler error.

  • Syntax : try-finallytry{ // Code to try here.}finally{ // Code to execute after try here.}

  • Syntax : try-catch-finallytry{ // Code to try here.}catch (System.Exception ex){ // Code to handle exception here.}finally{ // Code to execute after try (and possibly catch) here.}

  • Create and Throw int GetInt(int[] array, int index){ try { return array[index]; } catch(System.IndexOutOfRangeException e) { throw new System.ArgumentOutOfRangeException( "Parameter index is out of range."); }}

  • Partial Handling For example, a catch block could be used to add an entry to an error log, but then re-throw the exception to allow subsequent handling to the exception.try{ // try to access a resource}catch (System.UnauthorizedAccessException e){ LogError(e); // call a custom error logging procedure throw e; // re-throw the error}

  • Finally BlockA finally block allows clean-up of actions performed in a try block. If present, the finally block executes after the try and catch blocks execute. A finally block is always executed, regardless of whether an exception is thrown or whether a catch block matching the exception type is found.The finally block can be used to release resources without waiting for the garbage collector in the runtime to finalize the objects.

  • ExampleThe finally block is used to close a file opened in the try block. System.IO.FileStream file = null;System.IO.FileInfo fileinfo = new System.IO.FileInfo("C:\\file.txt");try{ file = fileinfo.OpenWrite(); file.WriteByte(0xF);}finally{ if (file != null) { file.Close(); }}

  • Web ServicesAn XML web service is a unit of code hosted by a web server that can be accessed using industry standards such as HTTP and XML.

  • OverviewXMLWeb ServiceWSProxyClient AppWeb ServerHTTP and XML

  • TechnologiesA discovery service UDDI (so clients can resolve the location of the XML web service) A description service WSDL (so clients know what the XML web service can do)A transport protocol HTTP GET, HTTP Post, SOAP (to pass the information between the client and XML web service)

  • Working with Web ServicesTwo steps: build a web service build clients to use it

  • Building a XML web service by handCreate a *.asmx file using any text editor

    using System;using System.Web.Services;namespace HelloWebService{public class HelloService{[WebMethod]public string HelloWorld(){return "Hello!";}}}

  • Test the XML web service

    Using WebDev.WebService.ext WebDev.WebServer /port:4000 /Path:F:\WebService

    Using IIS http://localhost/HelloWS/HelloWorldWebService.asmx

    The autogenerated test page DefaultWsdlHelpGenerator.aspx C:\Windows\Microsoft.NET\Framework\\CONFIG)

  • Building an XML web service using VisualStudio 2005Start by creating a project of type ASP.NET Web Service

  • A web service is ...One or more objects that respond to web-based method calls there is no GUI design to a web service only raw classes with methodspublic class Service1 : System.Web.Services.WebService{ }

  • ExampleLooks like C#, but keep in mind these are web-based methods client could be calling from any platform parameters passed using XMLpublic class Service1 : System.Web.Services.WebService{[WebMethod]public int Add(int x, int y){return x + y;}[WebMethod]public string[] Attendees(){

    }}attributeinherit

  • using System;using System.Text;using System.Collections;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.Web;using System.Web.Services; // contains Web service related classesnamespace HugeIntegerWebService{/// /// performs operations on large integers/// [ WebService(Namespace = "http://www.tempuri.org/",Description = "A Web service which provides methods that" +" can manipulate large integer values." ) ]public class HugeInteger : System.Web.Services.WebService{// default constructorpublic HugeInteger(){

  • // CODEGEN: This call is required by the ASP .NET Web// Services DesignerInitializeComponent();number = new int[ MAXIMUM ];}...

  • DeployingTo make your XML Web service available to others, you must deploy it to a Web server that is accessible to the clients you wish to support. To deploy the XML Web service to a server other than the development server, you can either add a Web Setup project or copy the required files to the destination server. In this walkthrough, you can choose how to deploy this XML Web service.

    There are two methods for deploying: 1) To deploy the XML Web service using a Web Setup project 2) To deploy the XML Web service by copying the project

  • 1) Using a web setup projectOn the File menu, point to Add, and then click NewProject.Select the Other node, then the Setup and Deployment Projects node, and then click Web Setup Project.In the Name box, type TempConvert1WebSetup, and then click OK. In the left pane of the File System Editor, select Web Application Folder.In Solution Explorer, right-click TempConvert1WebSetup, point to Add, and then click Project Output.In the Add Project Output Group dialog box, select ContentFiles.The Content Files group consists of the following files for the XML Web service: Service1.asmx, Global.asax, and Web.config.Click OK.In Solution Explorer, right-click the TempConvert1WebSetup project, and then on the shortcut menu, click Build. This creates a Windows Installer file in the local project directory. Executing this file installs the Web application.

  • 2) By copying the project In Solution Explorer, select the TempConvert1 project.On the Project menu, click Copy Web Site.Click the icon next to the Connect To dropdown box to open the Open Web Site dialog box. Browse to the location to which you want to copy the project.In the Source Web Site pane, select the files to copy and move them to the Remote Web Site pane by clicking the right-arrow icon. .Click Copy Web Site to copy the Web site.

  • UsesCross-platform application developmentLegacy system integration

  • Windows Service OverviewMicrosoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions.These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface.These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer.You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account.

  • CreatingWhen you create a service, you can use a Visual Studio project template called Windows Service. This template automatically does much of the work for you by referencing the appropriate classes and namespaces, setting up the inheritance from the base class for services, and overriding several of the methods you're likely to want to override.

    At a minimum, to create a functional service you must: Set the ServiceName property. Create the necessary installers for your service application.Override and specify code for the OnStart and OnStop methods to customize the ways in which your service behaves.

  • Steps for CreatingCreate a Windows Service project. In the Properties window, set the ServiceName property for your service. Set any of the following properties to determine how your service will function.CanStopCanShutdownCanPauseAndContinueCanHandlePowerEventAutoLog

    Access the Code Editor and fill in the processing you want for the OnStart and OnStop procedures.Override any other methods for which you want to define functionality.Add the necessary installers for your service application. Build your project by selecting Build Solution from the Build menu. Install the service.

  • Distributed ApplicationsThe application will consist of three logical tiers: data, business object, and user interface.The data tier is a database in SQL Server.The business-object tier will handle accessing the data and distributing it to the clients.The user-interface tier will consist of both a Web-based application and a traditional Windows application.

  • Unsafe ModeThe unsafe keyword denotes an unsafe context, which is required for any operation involving pointers. Example:unsafe static void FastCopy(byte[] src, byte[] dst, int count){ // Unsafe context: can use pointers here.}To compile unsafe code, you must specify the /unsafe compiler option. Unsafe code is not verifiable by the common language runtime.

  • Unsafe Mode Example// cs_unsafe_keyword.cs// compile with: /unsafeusing System;class UnsafeTest{ // Unsafe method: takes pointer to int: unsafe static void SquarePtrParam(int* p) { *p *= *p; } unsafe static void Main() { int i = 5; // Unsafe method: uses address-of operator (&): SquarePtrParam(&i); Console.WriteLine(i); }}Output: 25