Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Programming in c#

Related Books

Free with a 30 day trial from Scribd

See all

Related Audiobooks

Free with a 30 day trial from Scribd

See all
  • Be the first to comment

Programming in c#

  2. 2. Chapter : 1Introducing C#
  3. 3. What is C#? Is a compute-programming language developed byMicrosoft Corporation, USA. Is fully object-oriented language. Is first Component-oriented language. Suitable for developing Web-based applications Designed for developing robust, reliable & durablecomponents to handle real-world applications.
  4. 4. Highlights of C# Derived from C/C++ family. It simplifies & modernizes C++. It is only component oriented language available today. It is a language designed for the .NET Framework. It is a concise, lean & modern language. It combines the best features of many commonly usedlanguages: the productivity of VB, the power of C++, & theelegance of Java. It is intrinsically object-oriented & web-enabled. It has a lean & consistent syntax. Is simple, robust & productive. Major parts of .NET Framework are actually coded in C#.
  5. 5. Why C# ????? The primary motivation while developing any language is the concern that it able tohandle the increasing complexity of programs that are robust, durable &maintainable. The history of major languages developed is as follows:BPCL BCC++ANSI COakJavaANSI C++C#1967 19701972198319871991199519962000Dennis RitchieBjarne StroustrupANSI CommitteeJames GostlingSun MicroSystemsANSI CommitteMicrosoftMartin Richards Ken Thompson
  6. 6. Cont…. C & C++ languages suffer from anumber of shortcomings inmeeting World Wide Webrequirements & standards. Some are as follows:1. The high complexity of language2. They are not truly objectoriented3. They have poor type safety4. They are not suitable forworking with new webtechnologies.5. They do not support versioning6. Their low productivity7. They are weak in consistency8. Their poor compatibility withthe existing systems VB, a language promoted byMicrosoft for overcoming theseproblems, is not truly object-oriented and becomesincreasingly difficult to use whensystems become large. Java which is truly object-oriented has not retained somepowerful C++ features such asoperator overloading. Java also lacks inter-operabilitywith code developed in otherlanguages. Microsoft therefore decided todesign a new language. The result is C#, a simple &modern language that directlyaddresses the needs ofcomponent-based softwaredevelopment.
  7. 7. Evolution of C# The Internet is the mainstreamfor many business organizationtoday. There were a number oflimitations in using the WWWover the Internet:1. We could see only one site at atime2. The site had to be authored to ourhardware environment3. The information was basicallyread-only.4. We could not dynamicallycompare similar informationstored on different sites.5. The internet is a collection ofmany information islands that donot co-operate with each other. Microsoft wanted to develop asoftware platform which willovercome these limitations &make the Web bothprogrammable and intelligent. The outcome is a new generationplatform called .NET. Microsoft introduced C# as a defacto language of the .NETplatform. C# has been particularly designedto build software componentsfor .NET and it supports keyfeatures of .NET natively. C# compiler is embedded into.NET as shown below:.NET Framework.NET PlatformC#
  8. 8. Cont… C# is a descendant of C++ which in turn is adescendant of C as illustrated below:CC++Java C# VBConceptProductivityEleganceConceptComponentOrientationObjectOrentationPower
  9. 9. Characteristics of C# (5 marks) Simple C# simplifies C++ by eliminating irksome operators such as ->, ::, and pointers. C# treats integers & Boolean data types as entirely different types. Consistent C# supports an unified type system which eliminates the problem of varying ranges ofinteger types. All types are treated as objects. Modern C# is called modern language bcoz it supports: Automatic garbage collection Rich intrinsic model for error handling Decimal data types for financial applications Modern approach to debugging Robust security model Object-Oriented C# is truly object-oriented. It supports: Encapsulation Inheritance Polymorphism
  10. 10. Cont…. Type-Safe Type safety promotes robust programs. C# incorporates number of type-safe measures: All dynamically allocated objects & arrays are initialized to zero Use of any uninitialized variables produces an error message by the compiler Access to arrays are range-checked C# does not support unsafe casts C# supports automatic garbage collection Versionable Making new versions of software modules work with the existing applications isknown as versioning C# provides support for versioning with the help of new & override keywords. Compatible C# enforces the .NET common language specifications & therefore allows inter-operation with other .NET languages Interoperable C# provides support for using COM objects, no matter what language was used toauthor them. Fexible We may declare certain classes & methods as ‘unsafe’ and then use pointers tomanipulate them.
  11. 11. Applications of C# C# is a new language developed exclusively tosuit the features of .NET platform. It can be used for a variety of applications thatare supported by the .NET platform Console applications Windows applications Developing Windows Controls Developing ASP .NET Projects Creating Web Controls Providing Web Services Developing .NET component library
  12. 12. How Does C# differs from C++ ? Changes Introduced1. C# compiles straight from source code to executablecode, with no object files2. In C#, class definition does not use a semicolon atend3. The first character of Main() function is capitalized4. C# does not support #include statement5. C# does not support multiple code inheritance6. Casting in C# is much more safer then C++7. C# does not support default arguments8. C# permits declaration of variables between goto &label
  13. 13. How Does C# differs from C++ ? C++ Features Dropped1. Macros2. Multiple Inheritance3. Templates4. Pointers5. Global Variables6. Typedef statement7. Default Arguments8. Forward Declaration of Classes Enhancements to C++1. Automatic Garbage Collection2. Versioning Support3. Strict Type-Safety4. Properties to access data members5. Delegates & Events6. Boxing & Unboxing7. Web Services
  14. 14. How Does C# differs from Java ?1. C# has more primitive data types2. Arrays are declared differently in C#3. C# supports struct type & Java does not4. Java does not provide for operator overloading5. C# provides for better versioning support than Java6. C# provides static constructors for initialization7. Java does not directly support enumerations8. C# uses is operator instead of instanceof operator inJava9. C# checks overflows uses checked statements10. There is no labeled break statement in C#. The gotostatement is used to achieve this.11. In Java, the switch statement can have only integerexpression, while C# supports either an integer or stringexpressions
  15. 15. Chapter : 2Understanding .NET: The C# Environment
  16. 16. The .NET STRATEGY .NET is a software framework that includeseverything required for developing software forweb services. It integrates presentation technologies,component technologies & data technologies on asingle platform so as to enable users to developInternet applications.
  17. 17. The Origins of .NET Technology The current technology of .NET has gone through three different phases of development: OLE technology COM technology .NET technology OLE (Object Linking & Embedding) technology Developed by Microsoft to enable easy inter-process communications. OLE provides support to achieve following: To embed documents from one application into another application To enable one application to manipulate objects located in another application COM Technology: Overcomes the problems of maintaining and testing of software. A program can be divided into number of independent components where each one offers aparticular service. Each component can be developed & tested independently and then integrated into the mainsystem. This technology is known as Component Object Model (COM) and the software built using COM isreferred to as componentware. Benefits: Reduces Complexity Enhances software maintainability Enables distributed development acrossmultiple organizations
  18. 18. The Origins of .NET Technology (cont…) .NET Technology Is third generation component model Provides a new level of inter-operability compared to COM technology Inter-module communication is achieved using Microsoft IntermediaLanguage (MSIL) or simply IL IL allows for true cross language integration IL also provides metadata : describes characteristic of data includingdatatypes & locations. .NET also includes host of other languages & tools that enable us todevelop & implement Web-based applications easily.Fig : Three generations of component modelOLE TechnologyCOM Technology.NET TechnologyInterprocess CommunicationIntermodule CommunicationIntersite CommunicationPhase I – Early 1990sPhase II – 1995Phase III – Late 1990s
  19. 19. The .NET Framework.NET Framework.NET Building .NET DeviceBlock Services Software.NET Platform.NET UserExperience.NET Infrastructure& ToolsVisual Studio .NET Experience.NET Services.NET Infrastructure & ToolsWindows .NET .NET Framework
  20. 20. The .NET Framework (cont…) The .NET framework is one of the tools provided by the .NETinfrastructure & tools component of the .NET platform. The .NET framework provides an environment for building, deploying &running web services & other applications. It consists of three distinct technologies: Common Language Runtime Framework Base Classes User & program interfaces(ASP .NET)Framework Base Classes.NET FrameworkASP .NET(Web Services)Windows Forms(User Interface)Common Language Runtime
  21. 21. The Common Language Runtime (CLR) Is heat & soul of the .NET framework Is responsible for loading & running C#programs. Supports cross-language interoperability. Services provided: Loading & execution of programs Verification of type-safety Providing metadata Memory management Enforcement of security Interoperability with other systems Managing exceptions & errors Debugging
  22. 22. Components of CLR (cont…)Intermedia Language (IL)Common Type SystemCommon Language RuntimeExecution Support FunctionsSecurityGarbage CollectionClass LoaderMemory Layout
  23. 23. Framework Base Classes Allows to implement applications quickly The functionality of the base framework classes resides inthe namespace called System Provides: Input/Output operations String handling Managing arrays, lists,maps,etc Accessing files & file systems Accessing the registry Security Windowing Database management Drawing Managing errors & exceptions Connecting to Internet
  24. 24. User & Program Interfaces The .NET framework provides the following toolsfor managing user & application interfaces: Windows forms Web forms Console applications Web Services These tools enables users to develop user-friendlydesktop-based as well as web-based applications.
  25. 25. Benefits of the .NET Approach The .NET technology provides a number of benefits todevelopers & users. Some of them are: Simpler & faster systems development Enhanced built-in functionality Many different ways to communicate with the outsideworld Integration of different languages into one platform Easy execution Wide range of scalability Interoperability with existing applications Fewer bugs Potentially better performance
  26. 26. Chapter : 3Overview of C#
  27. 27. Introduction C# can be used to develop two categories ofprograms: Executable application programs & Component libraries Executable programs are written to carryoutcertain tasks & require Main method in one ofthe classes. Component libraries do not require Maindeclaration because they are not standaloneapplication programs. They are written for use by other applications.
  28. 28. A Simple C# Programclass SampleOne{public static void Main(){System.Console.WriteLine(“C# is sharper than C++”);}} Executing the program Save the above file with SampleOne.cs name Compile as : csc SampleOne.cs C# compiler compiles your code and create an executablefile by name SampleOne.exe For executing the program, simply type in the name of theexecutable file at the command prompt.
  29. 29. NAMESPACESSystem.Console.WriteLine(); Here System is a namespace in which the Console class islocated. This class can be accessed using the dot operator. C# supports using directive that can be used to import thenamespace System into the program.using System;class SampleTwo{public static void Main(){Console.WriteLine(“Hello World!!!”);}}
  30. 30. Adding Comments Enhances readability & understanding of thecode. Programs should have information such asimplementation details, change history and tasksperformed. Types of comments: Single-line comments (//) Multiline comments (/* ….. ….. */)
  31. 31. Main Returning a Value Main() can also return a value if it is declared as int instead ofvoid. When the return type is int, we must include a return statementat the end of the method.using System;class SampleThree{public static int Main(){Console.WriteLine(“Hello World!!!”);return 0;}} The value returned serves as the program’s termination statuscode. It allows communication of success or failure to the executionenvironment.
  32. 32. Using Aliases for NAMESPACE Classesusing A=System.Console;class SampleFour{public static void Main(){A.WriteLine(“Hello World!!!”);}}
  33. 33. Passing String Objects to WriteLine Methodusing System;class SampleFive{public static void Main(){string name=“PentaSoft Technologies”;Console.WriteLine(name);}}
  34. 34. Command Line Arguments Can be used to take an input from a user. Command line arguments are parameters supplied to theMain method at the time of invoking it for executionusing System;class SampleSix{public static void Main(string[] args){string name=“Welcome to”;Console.Write(name);Console.Write(“ ”+args[0]);Console.WriteLine(“ ”+args[1]);}}
  35. 35. MAIN with a Classclass Demo //class definition{public void display(){System.Console.WriteLine(“In Demo Class”);}}class SampleSeven{public static void Main(string[] args){Demo d=new Demo(); //creating d objectd.display(); //callinf display() function}}
  36. 36. Providing Interactive Inputusing System;class SampleEight{public static void Main(string[] args){Console.Write(“Enter Your Name”);string name=Console.ReadLine();Console.WriteLine(“Hello ”+name);}}
  37. 37. Using Mathematical Functionsusing System;class SampleNine{public static void Main(string[] args){double x=5.0;double y;y=Math.Sqrt(x);Console.WriteLine(“y = ”+y);}}
  38. 38. Multiple Main Methods In C# it is possible to have Mainmethod in different classes. In such situations there would bemultiple entry points in theprogram. There should be only one. This problem can be resolved byspecifying which Main is to beused to the compiler at the timeof compilation: csc filename.cs/main:classname Example : multimain.cs/main:ClassOR multimain.cs/main:Class B//multimain.csusing System;class A{public static void Main(){Console.Write(“Class A”);}}class B{public static void Main(){Console.Write(“Class B”);}}
  39. 39. Compile Time Errors A program is never totally error-free Types of errors: Syntax Errors Logic Errors Syntax errors will be caught by thecompiler Logical errors should be eliminated bytesting the program logic carefully. When the compiler cannot interpretwhat we are attempting to conveythrough our code the result is syntaxerror. Example:using Systom;class SampleTen{public static void main(){Console.Write(“Hello”);}} Errors.cs(2.7): error cs0234: The typeor namespace name ‘Systom’ does notexists in the class or namespace The error message contains:1. Name of the file beingcompiled(Errors.cs)2. Line number & column position of theerror(2.7)3. Error code as defined by the compiler(cs0234)4. Short description of error
  40. 40. Program Structure The documentation sectionconsists of a set of commentsgiving the name of theprogram, the author, date &other details. The using directive sectionincludes all those namespacesthat contain classes requiredby the application A interface is similar to aclass but contains onlyabstract classes.Used inmultiple inheritance A C# program may containmultiple class definitions. Every C# program requires aMain method as its startingpoint, the class containing theMain is the essential part ofprogram.Documentation SectionUsing Directive SectionInterfaces SectionClasses SectionMain Method SectionOptionalOptionalOptionalOptionalEssential
  41. 41. Chapter : 4Literals, Variables & Data Types
  42. 42. Literals Literals are the value constants assigned tovariables in a program. C# supports seven types of literals. Integral Literals : Decimal & Hexadecimal Integers Real Literals Boolean Literals :True / False Single Character Literals String Literals Backslash Character Literals : a, b, n, t, , ”
  43. 43. Variables Is an identifier that denotes a storage location used to storedata value. May take different values at different times duringprogram execution. Name should be meaningful. May consist of alphabets, digits & the underscore. Conditions: Not begin with a digit Uppercase & lowercase are distinct It should not be a keyword White space is not allowed Name can be of any length
  44. 44. Data Types Every variable in c# is associated with a data type Specifies the size and type of values that can be stored Types in C# Value types Reference types Pointers Values types are stored on stack When a value of a variable is assigned to another variable,the value is actually typed. Reference types are stored on heap When a value of a variable is assigned to another referencevariable, only the reference is copied.
  45. 45. Taxonomy C# data typesC# Data TypesValue Types Pointers Reference TypesPredefinedTypesUser-definedTypesPredefinedTypesUser-definedTypes•Integers•Real Numbers•Booleans•Characters•Classes•Arrays•Delegates•Interfaces•Objects•Strings•Enumerations•Structures
  46. 46. Declarations of Variables Variables are names of storage locations. Declaration does three things1. Tells the compiler what the variable name is.2. Specifies what type of data the variable will hold.3. The place of declaration decides the scopeof variable. Syntax: type variable1, variable2,……. variableN
  47. 47. Default Values A variable is either explicitly assigned a value or automaticallyassigned a default value. Following categories of variables are automatically initialized totheir default values. Static variables Instance variables Array elementsType Default ValueAll integer types 0char type ‘x000’float type 0.0fdouble type 0.0ddecimal type 0.0mbool type falseenum type 0All reference type null
  48. 48. Constant Variables Variables whose values do not change during theprogram execution are known as constants. Eg. const int Rows=10 const int Cols=10 Advantages Programs are easier to read & understand Programs are easier to modify Accidental errors are minimized
  49. 49. Scope of Variables It is region of code within which the variable can be accessed. Depends on type of the variable and its place of declaration. Consider following Eg…class ABC{static int m;int n;void fun(int x, ref int y, out int z, int[] a){int j=10;……..……..}} Static variables Declared at the class level Known as fields or field variables. The scope of these variables begins at the place of their declaration & ends when theMain method terminates. The value parameter ‘x’ will exists till the end of fun() method The reference & output parameters (y & z) do not create a new storage locations. Their scope is same as the underlying variables that are passed as arguments. Array element a[0] come into existence when an array instance is created, & ceaseto exist when there are no references to that array instance. Variables declared inside a method are called local variables. Their scope is until the end of block inside which they are declared.
  50. 50. Boxing & Unboxing In OOP, methods are invoked with the help of objects. Value types such as int & long are not objects, we cannotuse them to call methods. C# achieve this through a technique called as boxing. Boxing means the conversion of a value type on the stack toa object type on the heap. The conversion from an object type back to a value type isknown as unboxing.
  51. 51. Boxing Any type, value or reference can be assigned to an object without an explicitconversion. When a compiler finds a value type where it needs a reference type, it creates anobject ‘box’ into which it places the value of the value type. Example:int m=100;object om=m; //creates a box to hold m This code creates a temporary reference type ‘box’ for the object on heap. This can also be done with:int m=100;object om=(object)m; //C-style casting Here the variable m & om exist but the value of om resides on the heap. The valuesare independent of each m=100;object om=m;m=20;Console.WriteLine(m); //m=20Console.WriteLine(om); //om=10
  52. 52. Unboxing It is the process of converting the object type back to thevalue type. We can only unbox a variable that has previously beenboxed. Unboxing is an explicit operation using C-style m=100;object om=m; //box mint n=(int)om; //unbox om back to an int When unboxing a value, we have to ensure that the valuetype is large enough to hold the value of the object.
  53. 53. Chapter : 5Operators & Expressions
  54. 54. Type of OperatorsArithmetic operatorsRelational operatorsLogical operatorsAssignment operatorsIncrement & decrement operatorsConditional operatorsBitwise operatorsSpecial operators
  55. 55. Arithmetic OperatorsOperator Symbol Action ExampleAddition + Adds twooperandsx + ySubtraction - Subtracts the 2ndoperand with 1stoperandx – yMultiplication * Multiplies twooperandsx * yDivision / Divides twooperandx / yModulus % Gives theremainder whenthe operands aredivided.x % y
  56. 56. Exercise Write a program to demonstrate use of allArithmetic operators.
  57. 57. Relational Operators. Relational operators are used to compareexpressions. An expression containing a relational operatorevaluate to either true(1) or false (0).
  58. 58. Relational Operators.Syntax: (ae-1 relational operator ae-2)Operator SymbolEqual ==Greater than >Less Than <Greater than or equal to >=Less than or equal to <=Not Equal to !=
  59. 59. Exercise Write a program to demonstrate use of relationaloperators.
  60. 60. Logical operators Logical operators helps a user to combine two or more relationalexpressions into a single expression.Operator SymbolAND &&OR ||NOT !Bitwise logical AND &Bitwise logical Or |Bitwise logical exclusive Or ^
  61. 61. The Assignment Operator:- Used to assign the value of an expression to a variable. The assignment operator is the equal sign (=).Syntax : variable = expression;For e.g. a=b; C# also has a set of short assignment operator. Syntax: v op=exp Here ‘v’ is a variable, ‘exp’ is an expression & ‘op’ is an C# binary operator. The operator op= is known as shorthand assignment operator. Example: x+ = y+1; is same as x=x+(y+1); Advantages of shorthand assignment operators: Easier to read. The statement is more concise Results in more efficient code
  62. 62. C# Unary mathematical operators:-Operator Symbol Action ExamplesIncrement ++ Increments theoperand by one++x, x++Decrement -- Decrements theoperand by one--x, x--
  63. 63. Prefix and Postfix modes When used in prefix mode, the increment anddecrement operators modify their operand beforeit’s used. When used in postfix mode, the increment anddecrement operators modify their operand afterit’s used.
  64. 64. Exercise:- Write a program to demonstrate prefix andpostfix modes.
  65. 65. Conditional Operator Is C#’s only ternary operator. Takes three operators. Syntax : exp1 ? exp2 :exp3;Here if exp1 evaluates to true, then value of exp2is assigned else of exp3. Eg.a=10;b=15;x = (a > b) ? a :b;
  66. 66. Operator Precedence and Parentheses Some rules are needed about the order in which operations areperformed. This order, called operator precedence, is strictly spelled out in‘C# ‘Operators Relative Precedence* / % 1+ - 2
  67. 67. Type Conversion Used to convert data of one type to another type. Example:byte b1=10;byte b2=20;byte b3=b1+b2; Results in an error message because, when we add twobyte values, the compiler automatically converts them intoint types and the result is an integer. Hence code should be:int b3=b1+b2; //no error Ways of Type Conversion Implicit Conversions Explicit ConversionsType ConversionsImplicitConversionsExplicitConversionsArithmeticOperationsCastingOperations
  68. 68. Mathematical Functions Present in Math class of System Namespace. Static Members: E and PI Mathematical Methods in Math class:Method DescriptionSin() Sine of an angle inradiansCos() Cosine of an angle inradiansTan() Tanget of an angle inradiansAsin() Inverse of SineAcos() Inverse of CosineAtan() Inverse of TangentSinh() Hyperbolic sineCosh() Hyperbolic cosineTanh() Hyperbolic tangentSqrt() Square RootPow() Number raised to agiven powerExp() ExponentialLog() Natural logarithmAbs() Absolute valueMin() Lower of two numbersMax() Higher of two numbers
  69. 69. Exercise:- Write a program to find square root of number 25 Write a program to find minimum between twonumbers 25 & 35 using Math class.
  70. 70. Chapter : 6Decision Making & Branching
  71. 71. The if Statement Is a powerful decision making statement Used to control the flow of execution ofstatements General form:if (boolean-expression){statement-block;}statement-x;
  72. 72. Flowchart of simple if controlbooleanexpression?StatementblockStatement-XNext statementFalseTrueEntryJumping
  73. 73. Exercise Write a program that stores weight & height of10 person in array & count number of personwith height greater than 170 & weight more than55.
  74. 74. The IF….. ELSE Statement Is an extension of if statement. General form:if (boolean-expression){true-block statement (s);}else{false-block statement (s);}statement-x;
  75. 75. Flowchart of if…else controlbooleanexpression?True-BlockStatementStatement-XNext statementFalseTrueEntryFalse-BlockStatement
  76. 76. Exercise Write a program that counts total of even & oddnumbers stored in an array ‘number’.
  77. 77. Nesting of If….Else Statements Used when a series of decisions are involved. General form:if (test condition1){if (test condition2){statement-1;}else{statement-2;}}else{statement-3;}statement-x;
  78. 78. Flowchart of nested if….else statementsTestcondition1?Statement-3Statement-XNext statementTrueFalseEntryStatement-1Testcondition2?Statement-2TrueFalse
  79. 79. Exercise Write a program that finds largest among 3numbers using nested if..else statement.
  80. 80. The Else If Ladder Used when multipath decisions are involved. It is an chain of ifs in which the statement associated with each else is anif. General form:if (condition 1)statement-1;else if (condition 2)statement-2;else if (condition 3)statement-3;else if (condition n)statement-n;elsedefault-statement;statement-x;
  81. 81. Exercise Write a program that finds the grade of a studentusing else if ladder.
  82. 82. The Switch Statement If statements increases complexity of aprogram dramatically as thealternatives increases. The program becomes difficult to read& follow. C# offers an alternative with the help ofswitch statement General Form:switch(expression){case value-1:block-1break;case value-2:block-2break;------------------------------------------------------------default:default-blockbreak;}statement-x; Here, the expression must be an integertype or char or string type Value-1, value-2 … are constants orconstant expressions & are known ascase labels. Block-1, block-2…… are statement listsand may be zero or more statements.
  83. 83. Exampleusing System;class CityGuide{public static void main(){Console.WriteLine(“Select your choice”);Console.WriteLine(“London”);Console.WriteLine(“Bombay”);Console.WriteLine(“Paris”);Console.WriteLine(“Type your choice”);String name = Console.ReadLine ( );switch (name){case “Bombay”:Console.WriteLine(“Bombay : Guide 5”) ;beak;case “London”:Console.WriteLine(“london : Guide 10”) ;beak;case “Paris”:Console.WriteLine(“Paris : Guide 15”) ;beak;default:Console.WriteLine(“Invalid choise”) ;break;}}}
  84. 84. Fallthrough in Switch Statement In the absence of the breakstatement in a case block, if thecontrol moves to the next blockwithout any problem, it is knownas ‘fallthrough’. Fallthrough is permitted in C, C++ & Java. C# does not permit automaticfallthrough, if the case blockcontains some code. However, it is allowed if the caseblock is empty. If we want two consecutive caseblocks to be executedcontinuously, we have to force theprocess using the goto statement. Exampleswitch(m){case 1:x=y;goto case2;case 2:x=y+m;goto default;default:x=y-m;break;}
  85. 85. Chapter : 7Decision Making & Looping
  86. 86. The While Statement The process of repeatedlyexecuting a block of statements isknown as looping. Is an entry-controlled loopstatement. The test condition is evaluatedand if the condition is true, thenthe body of the loop is executed. Syntax:initialization;while(test condition){Body of the Loop…} Entry based loopBody of theloopTestcondTrueFalse
  87. 87. Exampleclass DowhileTest{public static void Main ( ){int two,count,y;two = 2;count=1;System.Console.WriteLine("Multiplication Table n");while(count<=10){y = two * count ;System.Console.WriteLine("2 * " + count + " = " + y) ;count = count + 1;}}}
  88. 88. The Do Statement On some occasions it might benecessary to execute the body ofthe loop before test is performed This can be handled using dostatement. Is an exit-controlled loopstatement. The body of the loop is executedat least once. Syntax:initialization;do{Body of the Loop…}while(test condition);Body of theloopTestcond• Exit based loopFalseTrue
  89. 89. Exampleclass DowhileTest{public static void Main ( ){int two,count,y;two = 2;count=1;System.Console.WriteLine("Multiplication Table n");do{y = two * count ;System.Console.WriteLine("2 * " + count + " = " + y) ;count = count + 1;}while ( count <= 10 ) ;}}
  90. 90. Exercise Program using do..while to print all the oddnumbers till 20
  91. 91. The For Statement Is an entry-controlled loop Syntax:for(initialization;testcondition;increment){Body of the loop…..} All the three actions, namely initialization,testing & incrementing, are placed in the forstatement itself.
  92. 92. Exercise Program using for loop to print multiplicationtable from 2 to 5
  93. 93. The FOREACH Statement Enables to iterate elements in an array. General form:foreach(type variable in expression){Body of the loop} The type & variable declares the iteration variable. During execution, iteration variable represents the arrayelement for which iteration is currently being performed. in is a keyword.
  94. 94. Exampleusing System;class ForeachTest{public static void Main(){int[] arryInt={11,22,33,44};foreach(int m in arryInt){Console.Write(" " + m);}Console.WriteLine();}}
  95. 95. Jumps in Loops C# permits a jump from one statement to the end orbeginning of a loop as well as jump out of a loop. Jumping Out of a loop An early exit from a loop can be accomplished by using thebreak & goto statements. Using break statement the loop is immediately exited andthe program continues with the statement immediatelyfollowing the loop. Skipping a Part of a Loop The continue statement causes the loop to continue withthe next iteration after skipping any statements in thebetween.
  96. 96. while(……….){………………….……………………if (condition)break;……………..……………..}……………..for (……….){………………if (error)break;……………..……………..}………………..Exit fromloopdo{……………………..if (condition)break;…………..…………..}while (…………….)……….for (……………….){…………for (………..){…………..if (condition)break;……………}……………}Exit fromloopExit fromloop Exit fromloopExiting a loop with break statement
  97. 97. while (test condition){…………if (………..)continue;………….………….}for (initialization; test condition; increment){…………if (………….)continue;……………………}do{………..if (………..)continue;………….…………..} while (test condition);Bypassing & Continuing in Loops
  98. 98. Labelled Jumps Used to jump a set of nested loops or to continue a loopthat is outside a current one. ExamplePublic static void Main(String a[]){if(a.Length==0)goto end;Console.WriteLine(a.Lenght);end; //Label nameConsole.WriteLine(“end”);}
  99. 99. Chapter : 8Methods in C#
  100. 100. Declaring Methods Methods are declared inside the body of a class General form:modifiers type methodname(formal-parameter-list){method---body} Method declaration has five parts: Name of the method Type of value the method returns List of parameters Body of the method Method modifiers Example:int Product(int x,int y){int m=x*y;return(m);}
  101. 101. Modifier Descriptionnew The method hides an inherited method with the same signature.public The method can be access from anywhere, including outside the class.protected The method can be access from within the class to which it belongs, or a typederived from that class.internal The method can be accessed from within the same program.private The method can only be accessed inside the class to which it belongs.static The method does not operate on a specific instance of the classvirtual The method can be overridden by a derived class.abstract A virtual method which defines the signature of the method, but doesn’tprovide an implementation.override The method overrides an inherited virtual or abstract method.sealed The method overrides an inherited virtual method, but cannot be overriddenby any class which inherit from this class. Must be used in conjunction withoverride.extern The method is implemented externally, in a different language.List of Method Modifiers
  102. 102. Invoking Methods Once method is defined, they must be activatedfor operations. Process of activating a method is known asinvoking or calling General form:objectname.methodname(actual-parameter-list);
  103. 103. Exampleusing System;class Method // class containing the method{// Define the Cube methodpublic int Cube(int x){return(x*x*x);}}// Client class to invoke the cube methodclass MethodTest{public static void Main( ){// Creat object for invoking cubeMethod M = new Method( );// invoke the cube methodint y = M.Cube(5); //Method call// Write the resultConsole.WriteLine(y);}}
  104. 104. Program for calling a static methodusing System;class StaticMethod{public static void Main(){double y = Square (2.5F); //Method CallConsole.WriteLine( y );}static double Square ( float x ){return ( x * x );}}
  105. 105. Nesting of Methods Methods can be invoked withoutusing an object & dot operator. A method can be called using onlyits name by another method ofthe same class. This is known as nesting ofmethods.using System;class Nesting{public void Largest ( int m, int n ){int large = Max ( m , n );Console.WriteLine( large );}int Max ( int a, int b ){int x= ( a > b ) ? a : b ;return ( x );}}class NestTesting{public static void Main( ){Nesting next = new Nesting ( ) ;next.Largest ( 100, 200 ) ;}}
  106. 106. Method Parameters For managing the process of passing values &getting back the results, C# employs four kinds ofparameters. Value Parameters Reference Parameters Output Parameters Parameter Arrays
  107. 107. Pass By Value By default, methodparameters are passed byvalue. When a method is invoked,the value of actualparameters are assigned tothe corresponding formalparameters. Any changes to formalparameters does not affectthe actual parameters. There are 2 copies ofvariables when passed byvalue.using System;class PassByValue{static void change (int m){m = m+10;}public static void Main( ){int x = 100;change (x);Console.WriteLine("x =" +x);}}
  108. 108. Pass By Reference We can force the value parameters tobe passed by reference. Use ref keyword. This does not create a new storagelocation. It represents the same storagelocation as the actual parameter. When a formal parameter is declaredas ref, the corresponding actualargument in the method invocationmust be declared as ref. Used when we want to change thevalues of variables in the callingmethod.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);Swap (ref m , ref n );Console.WriteLine("After Swapping;");Console.WriteLine("m = " + m);Console.WriteLine("n = " + n);}}
  109. 109. The Output Parameters Used to pass results back to the calling method. Declare the parameters with an out keyword. It does not create a new storage location. When a formal parameter is declared as out, the corresponding actual argument in the methodinvocation must also be declared as out.using System;class Output{static void Square ( int x, out int y ){y = x * x;}public static void Main( ){int m; //need not be initializedSquare ( 10, out m );Console.WriteLine("m = " + m);}}
  110. 110. Variable Argument Lists We can define methods that canhandle variable number ofarguments using parameterarrays. Parameter arrays are declaredusing the keyword params The parameter arrays should be aone-dimensional arrays.using System;class Params{static void Parray (params int [ ]arr){Console.Write("array elementsare:");foreach ( int i in arr)Console.Write(" " + i);Console.WriteLine( );}public static void Main( ){int [ ] x = { 11, 22, 33 };Parray ( x) ; //call 1Parray ( ) ; //call 2Parray ( 100, 200 ) ;//call 3}}
  111. 111. Method Overloading Enables us to create more than onemethod with the same name, but withthe different parameter lists &different definitions. Required when methods are requiredto perform similar tasks but usingdifferent input parameters. Exampleusing System;class Overloading{public static void Main(){Console.WriteLine(add(2,3));Console.WriteLine(add(2.6F,3.1F));Console.WriteLine(add(312L,22L,21));}static int add(int a,int b){return(a+b);}static float add(float a,float b){return(a+b);}static long add(long a,long b,int c){return(a+b+c);}}
  112. 112. Chapter : 9Handling Arrays
  113. 113. Introduction Array is a group of contiguous or related dataitems that share a common name. A particular value is indicated by writing anumber called index number or subscript inbrackets after the array name. Example : marks[10] The complete set of values is referred to as anarray. The individual values are called elements.
  114. 114. One-Dimensional Arrays A list of items can be given one variable name using only one subscript &such a variable is called a one-dimensional array. Declaration of Arrays: Syntax: type[] arrayname; Example: int[] counter;float[] marks;int[] x,y; Creation of Arrays: Syntax: arrayname = new type[size]; Example: counter=new int[5];marks=new float[4]; Combination:int[] counter=new int[5]; Initialization of Arrays: Syntax: arrayname[subscript]=value; Example: marks[0]=60;marks[1]=70;int[] counter={10,20,30,40,50};int len=c.Length; //Returns Length of Array
  115. 115. Exercise Write a program to sort an array of 5 numbertaking from user as input.
  116. 116. Two-Dimensional Arrays Allows to store table of values. Example: v[4,5]; Each dimension of the array is indexed from zero to itsmaximum size minus one. First index specifies the row & second index specifies thecolumn within that row. Declaration: int[,] myArray; Creation: myArray=new int[3,4]; Combination: int[,] myArray=new int[3,4]; Initialization: int[,] n={{0,0,0},{1,1,1}};
  117. 117. Exampleusing System;class MulTable{static int ROWS = 5;static int COLUMNS = 10;public static void Main( ){int[,] product =new int[ROWS,COLUMNS];int i,j;for (i=1; i<ROWS; i++){for (j=1; j<COLUMNS; j++){product[i, j] = i*j;Console.Write(" " +product[i , j]);}Console.WriteLine(" ");}}}
  118. 118. Variable-Size Arrays C# treats multidimensional arrays as ‘arrays of arrays’. It is possible to declare two-dimensional array as follows: int[][] x=new int[3][]; //three rows array x[0]=new int[2]; //first row has two elements x[1]=new int[4]; //second row has four elements x[2]=new int[3]; //third row has three elements These statements create a two-dimensional array havingdifferent length for each row. Also called as jagged arrays. Initializing: x[1][1]=10;
  119. 119. System.Array Class In C# every array we create is automatically derived fromthe System.Array class. Methods/properties present in this class:Method/Property PurposeClear() Sets a range of array elements to empty valuesCopyTo() Copies elements from source array to destinationarrayGetLength() Gives the number of elements in a givendimension of the arrayGetValue() Gets the value for a given index in the arrayLength Gets the lengths of an arraySetValue() Sets the value for a given index in the arrayReverse() Reverses the contents of a one-dimensional arraySort() Sorts the elements in a one-dimensional array.
  120. 120. Exampleusing System;class Sort{public static void Main( ){int[] x ={10,5,2,11,7};Console.WriteLine("Before Sort");foreach(int i in x)Console.WriteLine(" " + i);Console.WriteLine(" ");Array.Sort(x);Console.WriteLine("After Sort");foreach(int i in x)Console.WriteLine(" " + i);Console.WriteLine(" ");}}
  121. 121. ArrayList Class Present in System.Collections namespace. Can store a dynamically sized array of objects. Has an ability to grow dynamically. Example: ArrayList city=new ArrayList(30); Creates city with a capacity to store 30 objects. Default is 16. Adding Elements: city.Add(“Delhi”);city.Add(“Mumbai”); Removing Elements: city.RemoveAt(1); Modifying Capacity: city.Capacity=20;
  122. 122. Exampleusing System;using System.Collections;class Sort{public static void Main( ){ArrayList city=new ArrayList();city.Add("Delhi");city.Add("Mumbai");city.Add("Madras");city.Add("Kerela");Console.WriteLine("Capacity=" + city.Capacity);for(int i=0;i<city.Count;i++)Console.WriteLine(" " + city[i]);Console.WriteLine(" ");city.Sort();Console.WriteLine("After Sort");for(int i=0;i<city.Count;i++)Console.WriteLine(" " + city[i]);}}
  123. 123. ArrayList Property & MethodsMethod/Property PurposeAdd() Adds an object to a listClear() Removes all the elements from the listContains() Determines if an element is in the listCopyTo() Copies a list to anotherInsert() Inserts an elements into the listRemove() Removes the first occurrence of an elementRemoveAt() Removes the element at the specified placeRemoveRange() Removes a range of elementsSort() Sorts the elementsCapacity Gets or sets the number of elements in the listCount Gets the number of elements currently in thelist.
  124. 124. Chapter : 10Manipulating Strings
  125. 125. Introduction Represents a sequence of characters Example : string s1=“abc”’; Copying String:string s2=s1;string s2=String.Copy(s1); Concatenating String:string s3=s1+s2;string s3=string.Concat(s1,s2); Reading from keyboard:string s=Console.ReadLine(); Conversion:int num=111;string s=num.ToString(); Verbatim Strings: Starts with @ symbol. Tells the compilerto use string as verbatim string even if it includes escapescharacters.String s1=@”EGBCSharpString.cs”;tim
  126. 126. String Methods String objects are immutable. Thus we cannot modify the characters containedin them. However we can produce a modified version of astring using built in operations. Methods:Compare(), Concat(), Copy(), Equals(), Insert(),Join(), Replace(), Split(), ToLower(), ToUpper(),Trim(), TrimStart(), TrimEnd().
  127. 127. Exampleusing System;class demo{public static void Main(){string s1="Lean";string s2=s1.Insert(3,"r");string s3=s2.Insert(5,"er");string s4="Learner";string s5=s4.Substring(4);Console.WriteLine(s2);Console.WriteLine(s3);if(s3.Equals(s4))Console.WriteLine("Two Strings are Equal");Console.WriteLine("Substring="+s5);}}
  128. 128. Mutable Strings They cab be modified using StringBuilder class. Can grow dynamically. Also known as dynamic strings. Example:StringBuilder s=new StringBuilder(“abc”); Methods:Append(), Insert(), Remove(), Replace() Property:Capacity, Length, [ ]
  129. 129. Exampleusing System;using System.Text;class StringBuild{public static void Main(){StringBuilder s=new StringBuilder("Object ");Console.WriteLine("Original="+s);Console.WriteLine("Length="+s.Length);s.Append("Language");Console.WriteLine("Append="+s);s.Insert(6," Oriented ");Console.WriteLine("Inserted="+s);}}
  130. 130. Regular Expressions Provides a powerful tool for searching & manipulating alarge text. Used to: Locate substrings & return them Modify one or more substrings & return them Identify substrings that begin with or end with a pattern ofcharacters Find all words that begin with a group of characters andend with some other characters A regular expression (also known as pattern string) is astring containing two types of characters, Literals Metacharacters Literals are characters that we wish to search & match inthe text Metacharacters are special types of characters that givecommands to the regular expression parser.
  131. 131. Cont…. Examples of Regular Expression:Expression Meaning“bm” Any Word Beginning with m“erb” Any word Ending with er“bmS*erb” Any word beginning with m and ending with er“|,” Any word separated by spaces or commaSystem.Text.RegularExpressions supports a number ofclasses that can be used for searching, matching &modifying a text document.
  132. 132. Exampleusing System;using System.Text;//for StringBuilder classusing System.Text.RegularExpressions; //for Regex classclass RegexTest{public static void Main ( ){string str;str = "Amar, Akbar, Antony are friends!";Regex reg = new Regex (" |, ");StringBuilder sb = new StringBuilder( );int count = 1;foreach(string sub in reg.Split(str)){sb.AppendFormat("{0}: {1}n", count++, sub);}Console.WriteLine(sb);}}
  133. 133. Chapter : 11Structures & Enumerations
  134. 134. Structures We can create our own value types using structures. Used to pack data of different types. Syntax: Define Structurestruct struct-name{datamember1;datamember2;…….} The variables inside struct are called as members or fields or elements. Creating variables of new type:struct-name variablename;orstruct-name variablename = new struct-name(); Assigning values to Members:variablename.datamember1=value; Struct data members are private by default & hence declare them aspublic.
  135. 135. Exampleusing System;struct Item{public string name;public int code;public double price;}class StructTest{public static void Main( ){Item fan; = "Bajaj";fan.code = 123;fan.price = 1576.50;Console.WriteLine("Fan name: " +;Console.WriteLine("Fan code: " + fan.code);Console.WriteLine("Fan cost: " + fan.price);}}
  136. 136. Structs with Methods We can also assign values to data members using constructors. A constructor is a method which is used to set values of datamembers at the time of declaration.struct Number{int number;public Number (int value){number=value;}} The constructor is invoked as follows:Number num=new Number(190);
  137. 137. Exampleusing System;struct Rectangle{int a, b;public Rectangle ( int x, int y ) //constructor{a = x;b = y;}public int Area( ) //a method{return ( a * b );}public void Display ( ) //another method{Console .WriteLine("Area = " + Area( ) );}}class TestRectangle{public static void Main ( ){Rectangle rect = new Rectangle ( 10, 20 );rect.Display ( ); //invoking Display ( ) method}}
  138. 138. Difference between Classes & Structs (5 Marks)Category Classes StructsData Type Reference type & stored onheapValue Type & stored onstockInheritance Support Inheritance Do Not SupportInheritanceDefault Values Default value of a classtype is nullDefault value is the valueproduced by ‘zeroing out’the fields of structFieldInitializationPermit initialization ofinstance fieldsDo NotConstructors Permit declaration ofparameterless constructorsDo NotDestructors Supported Not SupportedAssignment Copies the referennce Copies the value
  139. 139. Enumerations Is a user defined integer type. Provides ways for attaching names to numbers. Enum keyword automatically enumerates list of words byassigning them values 0,1,2 & so on. General Form:enum Shape{Circle,Square,Triangle}Here Circle has value 0, Square has value 1 & Triangle hasvalue 2.
  140. 140. Exampleusing System;class Area{public enum Shape {Circle,Square}public void AreaShape ( int x, Shape shape){double area;switch (shape){case Shape.Circle:area = Math.PI * x * x;Console.WriteLine("Circle Area = "+area);break;case Shape.Square:area = x * x ;Console.WriteLine("Square Area = " +area);break;default:Console.WriteLine("Invalid Input");break;}}}class EnumTest{public static void Main( ){Area area = new Area ( );area.AreaShape ( 15, Area.Shape.Circle);area.AreaShape ( 15, Area.Shape.Square);area.AreaShape ( 15, (Area.Shape) 1 );area.AreaShape ( 15, (Area.Shape) 10 );}}
  141. 141. Chapter : 12Classes & Objects
  142. 142. Introduction C# is a true object oriented language. We create objects of a have class that have state& behavior. Object oriented language employ 3 coreprinciples: Encapsulation Inheritance Polymorphism.
  143. 143. Member Access Modifiers OOP provides data hiding A class may be designed to hide its members from outsideaccessibility. This is achieved using access specifiers. In C# all members have private access by default.Modifier Accessibility Controlprivate Member is accessible only from the class containing themember.public Member is accessible from anywhere outside the class aswell. Also accessible in derived classprotected Member is accessible only to its own class & in derivedclass.internal Member is available within the assembly or componentthat is being created but not to the clients of thatcomponent.protectedinternalAvailable in the containing program & in the derivedclass
  144. 144. Objects An object in C# is a block of memory that contains space tostore all the instance variable. Creating an Object:Rectangle rect; //declarerect=new Rectangle(); //instantiateOrRectangle rect=new Rectangle(); We can create ‘n’ number of objects of a class each having adifferent memory storage area. Accessing Class Members:objectname.variablename;objectname.methodname(parameter-list);
  145. 145. Exampleusing System;class Rectangle{public int length, width;public void GetData(int x, int y){length = x;width = y;}public int RectArea( ){int area = length * width;return (area);}}class Rect{public static void Main(){int area1;Rectangle rect1=new Rectangle();rect1.GetData(12,10);area1=rect1.RectArea();Console.WriteLine("Area="+area1);}}
  146. 146. Constructors Used to initialize an object when it iscreated. Have the same name as that of theclass. They do not have a return type.using System;class Rectangle{public int length, width;public Rectangle(int x, int y){length = x;width = y;}public int RectArea( ){int area = length * width;return (area);}}class Rect{public static void Main(){int area1;Rectangle rect1=new Rectangle(12,10);area1=rect1.RectArea();Console.WriteLine("Area="+area1);}}
  147. 147. Overloaded Constructors• Constructors with same name as of class butConstructors with same name as of class butdifferent no. & name of arguments.different no. & name of arguments.• Also known as polymorphism.Also known as polymorphism.using System;class Room{public int length, width;public Room(int x, int y){length = x;width = y;}public Room(int x){length = width=x;}public int RArea( ){int area = length * width;return (area);}}class Area{public static void Main(){int area1;Room r1=new Room(12,10);Room r2=new Room(12);area1=r1.RArea();Console.WriteLine("Area="+area1);area1=r2.RArea();Console.WriteLine("Area="+area1);}}
  148. 148. Static Members They are common to allthe objects. Are accessed without usinga particular object. Also referred as classvariables & class methods. A static variable iscommon to all instances ofa class. Even methods can bedeclared as static. Restrictions on StaticMethods: Can only call other staticmethods. Can only access staticdata. Cannot refer to this orbase in any way
  149. 149. Exampleusing System;class Mathopt{public static float mul(float x, float y){return(x*y);}public static float divide(float x, float y){return(x/y);}}class MathApp{public static void Main(){float a=Mathopt.mul(10,20);float b=Mathopt.divide(20,4);Console.WriteLine("Multiplication="+a);Console.WriteLine("Division="+b);}}
  150. 150. Static Constructors Is called before any object of a class is created. Useful to do any housekeeping work that needs to be done once. Used to assign initial values to static data members. Static constructor do not have any parameters. Example:class Abc{static Abc(){………}} A class can have only one static constructor
  151. 151. Copy Constructors A copy constructor creates an object by copyingvariables from another object. Example:public Item(Item item){code=item.code;price=item.price;}…………Item item2=new Item(item1); Here item2 is an copy of item1.
  152. 152. Destructors It is opposite to constructor. It is a method called when anobject is no longer required. The name of destructor issame as that of class name &is preceded by a tilde(~). They do not have a returntype. They do not take arguments. Example:class Fun{…….~Fun(){…..}} C# manages memorydynamically & uses agarbage collector, to executeall destructors on exit. This process is calledfinalization.
  153. 153. The This Reference This refers to the object that called the method. Used to distinguish between local & instance variables that have the samename. Example:class Integers{int x;int y;public void SetXY(int x, int y){this.x=x;this.y=y;}…..…..}
  154. 154. Constant Members (IMP) They are the variables whose value cannot be changedduring program execution. Example:public const int size=100; Any attempt to change the value of a constant result incompilation error. The const members are implicitly static. Const members are accessed using class name. Value must be set when cont is defined.
  155. 155. Read-Only Members (IMP) Allows us to decide the valueof a constant member at run-time. Also allows to have differentconstant values for differentobjects of the class. The value of the member isset using constructor &cannot be modified later. Can be declared as eitherstatic fields or instance fields. Example:class Numbers{public readonly int m;public static readonly int n;public Numbers(int x){m=x;}static Numbers(){n=100;}}
  156. 156. Properties (IMP) In C# private data members can only be accessed usingmethods of a class. Such methods are called as an accessor methods. Drawbacks of using these methods: We have to code them manually. User have to remember that they have to use accessormethods to work with data members. C# provides ‘properties’ that has same capabilities as ofaccessor methods. Using property we can access data members as if they arepublic. Also referred to as smart fields.
  157. 157. Exampleusing System;class Number{private int number;public int Anumber{get{return number;}set{number=value;}}}class PropertyTest{public static void Main(){Number n=new Number();n.Anumber=20;int m=n.Anumber;Console.WriteLine("Number="+m);}} Above class declares a get accessormethod (getter) & a set accessormethod (setter).
  158. 158. Property (cont…) A property can omit either a get clause or a set clause. A property that has only a getter is called a read-onlyproperty. A property that has only a setter is called a write-onlyproperty. Other features: Properties can also represent dynamic data. Properties are also inheritable. Can be used with static keyword.
  159. 159. Indexers (IMP) Indexers are locations indicators. Used to access class objects. An indexer looks like a property& is written like it but with 2differences: The indexer takes an indexargument & looks like an array. The indexer is declared usingkeyword this. Also referred to as smart arrays. Difference between indexers &properties: A property can be staticmember, whereas an indexer isalways an instance member. A get accessor of a propertycorresponds to a method withno parameters, whereas forindexer it corresponds to sameformal parameter list as theindexer. A set accessor of a propertycorresponds to a method with asingle parameter named value,whereas for indexer itcorresponds to same formalparameter list as theindexer,plus the paramternamed value. It is an error for an indexer todeclare a local variable with thesame name as an indexerparameter.
  160. 160. Exampleusing System;using System.Collections;class MyClass{private string []data = new string[5];public string this [int index]{get{return data[index];}set{data[index] = value;}}}class MyClient{public static void Main(){MyClass mc = new MyClass();mc[0] = “UniqueInfotech";mc[1] = “18";mc[2] = “Janardan Arcade";mc[3] = “Dahanu";mc[4] = “West";Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc[1],mc[2],mc[3],mc[4]);}}
  161. 161. Chapter : 13Inheritance & Polymorphism(IMP)
  162. 162. Introductoin Inheritance is a process of constructing ordesigning one class from another. Forms of Inheritance Classical form Containment formFeature XFeature YFeature ZFeature XFeature YFeature ZFeature PBase ClassDerived
  163. 163. Classical Inheritance Represents a kind of relationship between two classes. Example: Here class A is referred to as base class, parent class orsuper class. Class B is referred to as derived class, child class or subclass. Also referred to as ‘is-a’ relationship. Example: Dog is-a type of animal Ford is-a type of carClass AClass B
  164. 164. Different Classical Inheritance ImplementationABACBADCBABCGrandparent classParent classChild classSingle InheritanceHierarchicalInheritanceMultipleInheritanceMultilevelInheritance
  165. 165. Containment Inheritance Also known as containershipinheritance. Example:class A{….}class B{….A a; //a is contained in b}B b;…. Here object a is contained inobject b. This relationship is referredto as ‘has-a’ relationship. The outer class B whichcontains the inner class A istermed the ‘parent’ class &the contained class A istermed a ‘child’ class. Example: Car has-a radio. City has-a road.
  166. 166. Defining a Subclass Syntax:class subclass-name : baseclass-name{variable declaration;methods declaration;}
  167. 167. Example: Simple Inheritanceusing System;class Item{public void Company(){Console.WriteLine("Item Code=XYZ");}}class Fan:Item{public void Model(){Console.WriteLine("Model=Classic");}}class SimpleInheritance{public static void Main(){Fan f=new Fan();f.Company();f.Model();}}
  168. 168. Characteristic of Inheritance A derived class extends its direct base class. It can add newmembers to those it inherits. However, it cannot change orremove the definition of an inherited member. A derived class can hide an inherited member. A derived class can override an inherited member. An instance of a class contains a copy of all instance fieldsdeclared in the class & its base class. Constructors and destructors are not inherited.
  169. 169. Visibility Control Class Visibility : A class may be declared as: public: Accessible within & outside the program assembly internal (default): Accessible only within program assembly private: Accessible only within the class. Class Members Visibility : Can be declared as either: public private protected internal protected internalKeyword VisibilityContainingClassesDerivedClassesContainingProgramAnywhereOutside the programPrivate YProtected Y YInternal Y YP.Internal Y Y YPublic y Y y Y
  170. 170. Accessibility Constraints Constraints on the accessibility of members &classes when they are used in process ofinheritance: The direct base class of a derived class must be atleast as accessible as the derived class itself. Accessibility domain of a member is never largerthan that of the class containing it. The return type of a method must be as accessible asthe method itself.
  171. 171. Defining Subclass Constructorusing System;class Room{public int length;public int breadth;public Room(int x, int y){length=x;breadth=y;}public int Area(){return(length*breadth);}}class BedRoom:Room{int height;public BedRoom(int x,int y,intz):base(x,y){height=z;}public int Volume(){return(length*breadth*height);}}class InherTest{public static void Main(){BedRoom room1=newBedRoom(10,11,12);int area1=room1.Area();int vol=room1.Volume();Console.WriteLine("Area= "+area1);Console.WriteLine("Volume= "+vol);}}
  172. 172. Multilevel Inheritance Uses derived class as a super class Here A servers as base class for B which in turn serves as baseclass for C. The chain ABC is known as inheritance path. This process may be extended to any number of levels. Write a program to store & display student information usingmultilevel inheritance.ABCGrandparent classParent classChild class
  173. 173. Hierarchical InheritanceAccountCurrentFixed-DepositSavingsLongMediumShort Write a program to demonstrate use of hierarchical inheritance.
  174. 174. Method Overriding (IMP) In derived class we can create a method with samesignature as in base class. This concept is called as method overriding. This method can have same name, same arguments &same return type as a method in base class. When the method is called, the method defined in thesubclass is invoked & executed. The method in base class should be specified as virtual. The method in base class should be specified with keywordoverride.
  175. 175. Exampleusing System;class Super{public int x;public Super(int x){this.x=x;}public virtual void Display(){Console.WriteLine("Superx="+x);}}class Sub:Super{int y;public Sub(int x,int y) : base(x){this.y=y;}public override void Display(){Console.WriteLine("Superx="+x);Console.WriteLine("Sub y="+y);}}class Test{public static void Main(){Sub s1=new Sub(100,200);s1.Display();}}
  176. 176. Method Hiding (IMP) With the help of virtual & overridekeywords we can hide an methoddeclared in a base class. What if the class is provided bysomeone else? Here the base class method cannot bedeclared as virtual. To override such method use modifiernew to tell the compiler the derivedclass method “hides” the base classmethod. Example:using System;class Base{public void Display(){Console.WriteLine("Base Method");}}class Derived:Base{public new void Display(){Console.WriteLine("DerivedMethod");}}class HideTest{public static void Main(){Derived d=new Derived();d.Display();}}
  177. 177. Abstract Classes At times we can have one baseclass & a number of differentderived classes. The top-most base class simplyacts as a base for others & is notuseful on its own. We might not want to create anobjects of such classes. This can be done by making theclass as abstract. Example:abstract class Base{………}class Dervied:Base{……..}…….…….Base b1; //ErrorDerived d1; //Ok Characteristic: It cannot be instantiateddirectly. It can have abstract members. We cannot apply a sealedmodifier to it.
  178. 178. Abstract Methods Method declaration includesthe modifier abstract. It is implicitly a virtualmethod & does not provideany implementation. An abstract method does nothave a method body. Example:public abstract void Draw (intx, int y); Characteristics:1. It cannot haveimplementation.2. Its implementation must beprovided in non-abstractderived classes by overridingthe method.3. It can be declared only inabstract classes.4. It cannot take either staticor virtual modifiers.5. An abstract definition ispermitted to override avirtual method.
  179. 179. Sealed Classes: Preventing Inheritance Prevent a class from being further sub classed. Such classes are called sealed classes. Example:sealed class AClass{…..}sealed class BClass:Someclass{…..} Any attempt to inherit these classes will cause an error & compiler willnot allow it. Standalone utility classes are created as sealed classes.
  180. 180. Sealed Methods When an instance method declaration includes the sealed modifier, themethod is said to be a sealed method. A derived class cannot override this method. A sealed method is used to override an inherited virtual method with thesame signature. Example:class A{public virtual void Fun(){……}}class B: A{public sealed override void Fun(){……}} Now any derived class of B cannot further override the method Fun().
  181. 181. Polymorphism Means ‘one name ….. many forms’. Polymorphism can be achieved in two ways:PolymorphismInclusionPolymorphismOperationPolymorphismUsingVirtualMethodsUsingOverloadedMethods
  182. 182. Operation Polymorphism Implemented using overloaded methods & operators. Overloaded methods are selected for invoking by matchingarguments, in terms of number, type & order. This information is known to compiler at compile time. Also called as early binding, or static binding or staticlinking. Also known as compile time polymorphism. Early binding means an object is bound to its method callat compile time.
  183. 183. Exampleusing System;class Dog{}class Cat{}class Operation{static void Call(Dog d){Console.WriteLine("Dog iscalled");}static void Call(Cat c){Console.WriteLine("Cat iscalled");}public static void Main(){Dog dog=new Dog();Cat cat=new Cat();Call(dog);Call(cat);}}
  184. 184. Inclusion Polymorphism Achieved through use of virtual functions. Assume class A implements virtual method M. Classes B &C are derived from A and override method M. When B iscast to A, a call to method M from A is dispatched to B.Similarly when C is cast to A, a call to method M from A isdispatched to C. Also known as run-time polymorphism. Since method is linked with a particular class much laterafter compilation, this process is also called late binding. Also known as dynamic binding as the selection of methodis done dynamically at run time.
  185. 185. Exampleusing System;class Maruti{public virtual void Display(){Console.WriteLine("Maruti Car");}}class SX4:Maruti{public override void Display(){Console.WriteLine("SX4 Car")}}class Swift:Maruti{public override void Display(){Console.WriteLine("Swift Car");}}class Inclusion{public static void Main(){Maruti m=new Maruti();m=new SX4();m.Display();m=new Swift();m.Display();}}
  186. 186. Chapter : 14Interfaces: Multiple Inheritance
  187. 187. Introduction C# does not support multiple inheritance. A class cannot have more than one superclass. C# provides an approach known as interface tosupport the concept of multiple inheritance. An interface is a class with some differences: All members of an interface are implicitly public &abstract. An interface cannot contain constant fields,constructors & destructors. Its members cannot be declared static
  188. 188. Defining an Interface General Form:interface Interfacename{member declarations;} Like classes, interfaces can also be extended. That is, an interface can be sub interfaced from other interfaces. General Form:interface name2:name1{Members of name2} Note: An interface can not extend classes
  189. 189. Example: 1using System;interface Addition{int Add();}interface Multiplication{int Mul();}class Computation:Addition,Multiplication{int x,y;public Computation(int x,int y){this.x=x;this.y=y;}public int Add(){return(x+y);}public int Mul(){return(x*y);}}class InterfaceTest{public static void Main(){Computation com=new Computation(10,20);Addition add=(Addition)com; //castingConsole.WriteLine("Sum="+add.Add());Multiplication mul=(Multiplication)com;Console.WriteLine("Product="+mul.Mul());}}
  190. 190. Example: 2 --- Multiple Implementation of an Interfaceusing System;interface Area{double Compute(double x);}class Square:Area{public double Compute(double x){return(x*x);}}class Circle:Area{public double Compute(double x){return(Math.PI*x*x);}}class Interface2{public static void Main(){Square s=new Square();Circle c=new Circle();Area area;area=s as Area;Console.WriteLine("Area ofSquare="+area.Compute(10.2));area=c as Area;Console.WriteLine("Area ofSquare="+area.Compute(10.2));}}
  191. 191. Interfaces & Inheritance A base class of a derived class mayimplement an interface. When an object of the derived class isconverted to the interface type, theinheritance hierarchy is searched for aclass that directly implements theinterface. Example:using System;interface Display{void Print();}class B:Display{public void Print(){Console.WriteLine("BaseDisplay");}}class D:B{public new void Print(){Console.WriteLine("DerivedDisplay");}}class Interface3{public static void Main(){D d=new D();d.Print();Display dis=(Display)d;dis.Print();}}
  192. 192. Explicit Interface Implementation It may be possible that multipleinterface have a method of a samename. This may create a problem when aclass implements more than oneinterface. C# supports a technique known asexplicit interface implementation,which allows a method to specifyexplicitly the name of the interface itis implementing. Example:using System;interface I1{void display();}interface I2{void display();}class C1:I1,I2{void I1.display(){Console.WriteLine("I1 Display");}void I2.display(){Console.WriteLine("I2 Display");}}class Interface4{public static void Main(){C1 c=new C1();I1 i1=(I1)c;i1.display();I2 i2=(I2)c;i2.display();}}
  193. 193. Abstract Class & Interfaces An abstract class can use an interface in the base class list. Here the interface methods are implemented as abstract methods. Example:interface A{void Method();}abstract class B:A{……….……….public abstract void Method();} Here class B does not implement the interface method; it simply redeclares as apublic abstract method. It is the duty of the class that derives from B to override & implement the method.
  194. 194. Chapter : 15Operator Overloading
  195. 195. Introduction The C# operators can be defined to work with the user-defined datatypes such as structs & classes. C# has the ability to provide the operators with a special meaningfor a data type. This mechanism of giving such special meaning to an operator isknown as operator overloading. Following is list of operators that can be overloaded.Category Operators1. Binary Arithmetic +,*,/,-,%2. Unary Arithmetic +,-,++,--3. Binary bitwise &,|,^,<<,>>4. Unary bitwise !,~,true,false5. Relational Operators ==,!=,>=,<,<=,>
  196. 196. Cont… Following is list of operators that cannot be overloaded.Category Operators1. Conditional operators &&,||2. Compound assignment +=,-=,*=,/=,%=3. Other operators [ ],( ),=,?:,->,new,sizeof,typeof,is,as
  197. 197. Need for Operator Overloading Operator overloading gives us syntactical convenience. It helps us to generate more readable code in a number ofsituations. These includes: Financial programs. Mathematical or physical modeling Graphical programs Text manipulations General form of an operator method:public static retval operator op(arglist){Method body…..}
  198. 198. Overloading Unary Operatorsusing 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);Console.WriteLine();}public static Space operator -(Space s){s.x=-s.x;s.y=-s.y;s.z=-s.z;return(s);}}class SpaceTest{public static void Main(){Space s=new Space(10,-20,30);Space q;Console.Write("S: ");s.Display();q=-s;Console.Write("Q: ");q.Display();}}
  199. 199. Overloading Binary Operatorsusing System;class Complex{double x,y;public Complex(){ }public Complex(double real,doubleimag){x=real;y=imag;}public 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.Write(" + j"+y);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;c.display();}}
  200. 200. Overloading Comparison Operators C# supports six comparison operators that can beconsidered in three pairs: == & != > & <= < & >= The significance of pairing is two-fold: Within each pair, the second operator should alwaysgive exactly the opposite result to the first. C# always requires us to overload the comparisonoperators in pairs. That is, if we overload ==, then wemust overload != also, otherwise it is an error.
  201. 201. Example:using System;class Vector{int x,y,z;public Vector(int a,int b,int c){x=a;y=b;z=c;}public static bool operator ==(Vectorv1,Vector v2){if(v1.x==v2.x && v1.y==v2.y)return(true);elsereturn(false);}public static bool operator !=(Vectorv1,Vector v2){return(!(v1==v2));}}class CompareTest{public static void Main(){Vector u1=new Vector(1,2,3);Vector u2=new Vector(1,2,3);if(u1==u2)Console.WriteLine("U1 is equal toU2");elseConsole.WriteLine("U1 is not equal toU2");}}
  202. 202. Chapter : 16Delegates & Events(IMP)
  203. 203. Introduction A delegate object is a special type of object that containsthe details of a method rather than data. Delegates in C# is used for two purposes: Callback Event Handling Dictionary meaning of delegate is “a person acting foranother person”, in C# it means a method acting foranother method. A delegate in C# is a class type object & is used to invoke amethod that has been encapsulated into it at the time of itscreation.
  204. 204. Delegate Declaration General Form: modifier delegate return-type delegate-name(parameters); Delegate is derived from System.Delegate class. The modifier controls the accessibility of the delegate. Delegate may take any of the following modifiers:new, public, private, protected, internal. It is a class type & can be declared in any place where aclass definition is permitted. A delegate may be defined in the following places: Inside a class Outside all classes As the top level object in a namespace.
  205. 205. Delegate Methods The methods whose references are encapsulatedinto a delegate instances are known as delegatemethods (or callable entities) The signature & return type of delegate methodsmust exactly match the signature & return typeof the delegate.
  206. 206. Delegate Instantiation A delegate-creation-expression is used to create a new instance ofa delegate. General Form: new delegate-type(expression) Here the delegate-type is the name of the delegate declaredearlier whose object is to be created. Expression must be the method name. The method & the object to which a delegate refers aredetermined when the delegate is instantiated. This remains constant for the entire lifetime of the delegate. It is not possible to change them, once the delegate is created.
  207. 207. Delegate Invocation When a delegate is invoked, it in turn invokesthe method whose reference has beenencapsulated into the delegate. General Form: delegate_object(parameter list); The optional parameter list provides values for theparameters pf the method to be used.
  208. 208. Example:using System;//Delegate Declarationdelegate int ArithOp(int x,int y);class MathOperation{public static int Add(int a,int b){return(a+b);}public static int Sub(int a,int b){return(a-b);}}class DelegateTest{public static void Main(){ArithOp op1=newArithOp(MathOperation.Add);ArithOp op2=newArithOp(MathOperation.Sub);int result1=op1(3,20);int result2=op2(40,20);Console.WriteLine("Result1="+result1);Console.WriteLine("Result2="+result2);}}
  209. 209. Multicast Delegate It is possible for delegates to hold & invoke multiplemethods. Such delegates are called multicast delegates. Also known as combinable delegates. They must satisfy following conditions: Return type of such delegate must be void. None of the parameters of the delegates can be declared asoutput parameters, using out keyword. If D is a delegate & d1,d2,d3 & d4 are its instances, thenthe statements: d3=d1+d2 //refers to two methods. d4=d3-d2 //refers to only d1 method
  210. 210. Exampleusing System;delegate void MDelegate();class DM{public static void Display(){Console.WriteLine("In Display");}public static void Print(){Console.WriteLine("In Print");}}class MDelegateTest{public static void Main(){MDelegate m1=newMDelegate(DM.Display);MDelegate m2=newMDelegate(DM.Print);MDelegate m3=m1+m2;MDelegate m4=m2+m1;MDelegate m5=m3-m2;m3();m4();;m5();}}
  211. 211. Events(IMP) An event is a delegate type class member that is used bythe object or class to provide a notification to other objectthat an event has occurred. The client object can act on an event by adding an eventhandler to the event. General Form: modifier event type event-name; Since events are based on delegates, we must first declarea delegate and then declare an instance of the delegateusing the keyword event.
  212. 212. Exampleusing System;//Delegate Declarationdelegate void EDelegate(string str);class EventClass{public event EDelegate Status;public void TriggerEvent(){Status("Event Triggered");}}class EventTest{public static void Main(){EventClass ec=newEventClass();EventTest et=newEventTest();ec.Status+= newEDelegate(et.EventCatch);ec.TriggerEvent();}public void EventCatch(stringstr){Console.WriteLine(str);}}
  213. 213. Chapter : 17Managing Console I/O Operations
  214. 214. The Console Class The methods for reading & writing to the console areprovided by the System.Console class. This class gives us access to the standard input, standardoutput & standard error streams:Stream Object RepresentsConsole.In Standard InputConsole.Out Standard OutputConsole.Error Standard Error
  215. 215. Console Input Supports two methods for obtaining input fromthe keyboard. Read(): Returns a single character as int. ReadLine(): Returns a string containing a line of text.
  216. 216. Console Output Supports two methods for writing to the console. Write(): Outputs one or more values to the screenwithout a new line character. WriteLine(): Outputs one or more values to thescreen but adds a new line character at the end of theoutput.
  217. 217. Exercise Write a program in C# to print the followingoutput:12 23 3 34 4 4 45 5 5 5 56 6 6 6 6 67 7 7 7 7 7 78 8 8 8 8 8 8 89 9 9 9 9 9 9 9 9
  218. 218. Formatted Output Use overloaded WriteLine()method. General Form: Console.WriteLine(format-string, v1, v2, ….); Format String contains bothstatic text & markers whichindicate Where the values are to be printed. How the values are to be formatted. Example Console.WriteLine(“Sum of {0}and {1} is {2}”,a,b,c); We can also specify a width forthe value using the format: { n , w } n is the index number w is the width for the value Example:int a=45;int b=976;int c=a+b;Console.WriteLine(“{0,5n+{1,5}n} ------- n{2,5}”,a,b,c);4 5+ 9 7 6-----------1 0 2 1
  219. 219. Numeric Formatting
  220. 220. Chapter : 18Managing Errors & Exceptions

    Be the first to comment

    Login to see the comments

  • SubhasisDas1

    Sep. 14, 2017
  • RadhaRavi5

    Oct. 2, 2017
  • BasavarajGabale

    Oct. 3, 2017
  • FaizanShaikh83

    Oct. 4, 2017
  • AminKhan81

    Oct. 29, 2017
  • AthanasiosEmmanouili

    Nov. 18, 2017
  • YanivTal5

    Dec. 6, 2017
  • ChesterNaguit

    Jan. 19, 2018
  • PriyankaPatel359

    Jul. 4, 2018
  • IndunilWanasinghe1

    Jan. 2, 2019
  • Emadezz2

    Jan. 24, 2019
  • PallaviKhavse

    Jan. 28, 2019
  • Aravindkumar113

    May. 14, 2019
  • AnilKashyap34

    May. 27, 2019
  • hteixe

    Jun. 19, 2019
  • KhaledMoustafa21

    Jul. 21, 2019
  • PawanSingh103

    Aug. 31, 2019
  • angelicaroseBaes

    Oct. 14, 2019
  • HussainMuhammad9

    Jan. 8, 2020
  • ArchaNaBabu14

    Jul. 18, 2020


Total views


On Slideshare


From embeds


Number of embeds