The document provides an overview of key concepts in object-oriented programming using C#, including classes, inheritance, abstract classes, sealed classes, files, delegates, interfaces, parameters, method overloading, operator overloading, and indexers. It includes examples and exercises to demonstrate these concepts.
The document discusses various concepts related to abstraction in software development including project architecture, code refactoring, enumerations, and the static keyword in Java. It describes how to split code into logical parts using methods and classes to improve readability, reuse code, and avoid repetition. Refactoring techniques like extracting methods and classes are presented to restructure code without changing behavior. Enumerations are covered as a way to represent numeric values from a fixed set as text. The static keyword is explained for use with classes, variables, methods, and blocks to belong to the class rather than object instances.
In this chapter we will understand how to define custom classes and their elements. We will learn to declare fields, constructors and properties for the classes. We will revise what a method is and we will broaden our knowledge about access modifiers and methods.
Here we are going to learn why is a good practice to use interfaces and how they are different from abstraction classes. Further more we are going to see how which one of them to use.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
油
The document discusses Java syntax and concepts including:
1. It introduces primitive data types in Java like int, float, boolean and String.
2. It covers variables, operators, and expressions - how they are used to store and manipulate data in Java.
3. It explains console input and output using Scanner and System.out methods for reading user input and printing output.
4. It provides examples of using conditional statements like if and if-else to control program flow based on conditions.
Encapsulation provides benefits such as reducing complexity, ensuring structural changes remain local, and allowing for validation and data binding. It works by hiding implementation details and wrapping code and data together. Objects use private fields and public getters/setters for access. Access modifiers like private, protected, and public control visibility. Validation occurs in setters through exceptions. Mutable objects can be modified after creation while immutable objects cannot. The final keyword prevents inheritance, method overriding, or variable reassignment.
This document discusses polymorphism, abstract classes, and abstract methods. It defines polymorphism as an object's ability to take on many forms and describes how it allows reference variables to refer to objects of child classes. It also distinguishes between method overloading and overriding, and explains the rules for each. Abstract classes are introduced as classes that cannot be instantiated directly but can be inherited from, and it is noted they may or may not contain abstract methods.
This document provides an introduction and overview of inheritance in C#, including:
- Inheritance allows classes to extend existing classes, inheriting members and behavior
- Derived classes can call base class constructors via the base keyword
- The protected keyword controls accessibility for inherited members
- Virtual and override enable dynamic binding and polymorphism by allowing derived classes to override base class methods
- Abstract classes define common interfaces for derived classes to implement
Inheritance allows classes to extend and inherit properties from base classes. This creates class hierarchies where subclasses inherit and can override methods from superclasses. Inheritance promotes code reuse through extension when subclasses share the same role as the base class. Composition and delegation are alternative approaches to code reuse that may be preferable in some cases over inheritance.
The document discusses various object-oriented programming concepts in C#, including abstraction, encapsulation, inheritance, polymorphism, interfaces, abstract classes, virtual methods, classes, sealed classes, and provides code examples for foreach loops, switch statements, arrays, data types, boxing and unboxing, overloading and overriding, interfaces, classes vs. structures, access modifiers, abstract classes, and sealed classes.
This document provides an introduction to creating and using classes in C#. Key points covered include defining classes with fields, methods, and constructors; using accessibility modifiers like public and private; calling methods and using the this keyword; creating static methods; and using listboxes, comboboxes, and events for selection changes. Examples are provided for defining classes, constructors, static and instance methods, and populating and accessing selection properties of list and combo boxes.
18CSS101J PROGRAMMING FOR PROBLEM SOLVINGGOWSIKRAJAP
油
The document discusses various operators, control statements, and arrays in C programming. It begins by explaining operator precedence and types of operators such as relational, logical, increment, assignment etc. It then covers control statements including if-else, switch case, for, while, do-while loops. It also discusses goto, break and continue statements. Finally, it describes arrays including initialization, declaration, accessing elements and array operations. The document provides examples to explain the concepts in detail.
This document discusses exception handling in .NET. It defines exceptions as objects that are thrown when errors or unexpected events occur during program execution. Exceptions allow errors to be handled at multiple levels through try-catch blocks. The core exception class is System.Exception, which other custom exceptions inherit from. Exceptions can be thrown manually with throw or occur automatically from errors. Finally blocks ensure code is always executed even if an exception is thrown.
The document discusses classes, methods, and objects in C#. It explains that classes define methods and properties, and methods perform actions and can take parameters and return values. It provides examples of commonly used methods in classes like Console, Math, and Random. It also discusses how to define classes with data members and methods, and how to create objects from classes which allows calling instance methods on those objects. Classes serve both as program modules containing static methods and data, and as blueprints for generating objects with their own state and behavior.
The document discusses various C# programming concepts related to core C# and object-oriented programming, including parameter passing in C#, value types vs reference types, structs, enums, arrays, access modifiers, constructors, and properties. It provides code examples to demonstrate these concepts.
This document provides an overview of the C++ programming language. It discusses key C++ concepts like classes, objects, functions, and data types. Some key points:
- C++ is an object-oriented language that is an extension of C with additional features like classes and inheritance.
- Classes allow programmers to combine data and functions to model real-world entities. Objects are instances of classes.
- The document defines common C++ terms like keywords, identifiers, constants, and operators. It also provides examples of basic programs.
- Functions are described as modular and reusable blocks of code. Parameter passing techniques like pass-by-value and pass-by-reference are covered.
- Other concepts covered include
The document discusses arrays, strings, and functions in C programming. It begins by explaining how to initialize and access 2D arrays, including examples to take input from the user and store it in a 2D array. It then discusses initializing and accessing multidimensional arrays. Next, it covers array contiguous memory and the advantages and limitations of arrays. Finally, it discusses common programming errors related to array construction for real-time applications.
In this chapter we are going to get familiar with recursion and its applications. Recursion represents a powerful programming technique in which a method makes a call to itself from within its own method body. By means of recursion we can solve complicated combinatorial problems, in which we can easily exhaust different combinatorial configurations, e.g. generating permutations and variations and simulating nested loops. We are going to demonstrate many examples of correct and incorrect usage of recursion and convince you how useful it can be.
In this chapter we will discuss exceptions in the object-oriented programming and in Java in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct.
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
油
The document summarizes key topics related to recursion, pointers, and dynamic memory management in C programming:
Recursion is introduced as a process where a function calls itself repeatedly to solve a problem. Examples of recursive functions like factorial, Fibonacci series, and Towers of Hanoi are provided.
Pointers are defined as variables that store the memory addresses of other variables. Pointer operations like incrementing, decrementing, and arithmetic are described. The use of pointers to pass arguments to functions and access array elements is also demonstrated.
Dynamic memory allocation functions malloc(), calloc(), and realloc() are explained along with examples. These functions allocate and manage memory during run-time in C programs.
Object Oriented Programming using C++ Part IIIAjit Nayak
油
The document discusses inheritance in object-oriented programming. It defines inheritance as a technique where a new subclass inherits attributes and behaviors from an existing superclass without needing to redefine them. This allows code reuse and reduces development costs. The document provides examples of single inheritance with classes like Employee and Manager, and multi-level inheritance with Student, Test, and Result classes. It also discusses polymorphism through method overriding and different types of inheritance like public, private and protected.
Esoft Metro Campus - Diploma in Information Technology - (Module IX) Programming with C#.NET
(Template - Virtusa Corporate)
Contents:
Introduction to .NET Framework
.NET Framework Platform Architecture
Microsoft Visual Studio
C# Language
C#, VS and .NET Framework Versions
Your First C# Application
Printing Statements
Comments in C#
Common Type System
Value Types and Reference Type
Variables Declaration in C#
Type Conversion
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
If Statement
If Else Statement
If Else if Else Statement
Nested If Statement
Switch Statement
While Loop
Do While Loop
For Loop
Arrays
Accessing Arrays using foreach Loop
Two Dimensional Arrays
Classes and Objects in C#
Inheritance in C#
Partial Classes
Namespaces
Windows Forms Applications
Using Buttons, Labels and Text Boxes
Displaying Message Boxes
Error Handling with Try Catch finally
Using Radio Buttons
Using Check Boxes
Using List Boxes
Creating Menus
Creating ToolStrips
MDI Forms
Database Application in C#
Creating a Simple Database Application
SQL Insert / Update / Retrieving / Delete
SQL Command Execute Methods
Data Sets
The document discusses exception handling in C# programs. It explains that exceptions are errors that occur during program execution. The C# try, catch, and finally keywords are used to handle exceptions. The try block contains code that might cause exceptions. The catch block handles specific exception types. The finally block contains cleanup code that always executes. Built-in exceptions like DivideByZeroException are part of the .NET Framework. Exception handling prevents program crashes and allows graceful handling of errors.
The document discusses classes and methods in C#. It defines a class as a blueprint for creating objects with common properties and methods. A class declaration defines the data members (fields) and function members (methods) of the class. Methods are functions defined within a class that can access and modify the class's fields and other methods. The document covers various ways of passing parameters to methods, including value parameters, reference parameters, output parameters, and parameter arrays. It provides examples of defining classes with fields and methods, as well as invoking methods and passing parameters.
The document discusses call by value vs call by reference in functions, and different storage classes in C including auto, extern, register, and static. It provides examples of each storage class and how they determine the scope and lifetime of variables. It also discusses recursion and provides examples of recursive functions to calculate factorial, sum of natural numbers, Fibonacci series, and solve the Towers of Hanoi problem.
The document discusses control statements in C# programming. It describes selection statements like if, if-else, switch-case that are used to change the flow of program execution. It also covers iterative statements like while, do-while and for loops that are used to repeat blocks of code. Examples are provided to demonstrate nested if statements, stacking if statements, reversing a number using while loop, counting digits in a number, and calculating average of numbers entered by user.
In this chapter we will get more familiar with what methods are and why we need to use them. The reader will be shown how to declare methods, what parameters are and what a methods signature is, how to call a method, how to pass arguments of methods and how methods return values. At the end of this chapter we will know how to create our own method and how to use (invoke) it whenever necessary. Eventually, we will suggest some good practices in working with methods. The content of this chapter accompanied by detailed examples and exercises that will help the reader practice the learned material.
The document describes a program with 6 functions to help elementary school students learn math. The functions include easy and hard addition, subtraction, a grade converter, and a letter grade function. Each function is defined to perform a specific math operation or conversion, such as adding two numbers or converting a percentage to a letter grade. The program is intended to help students learn math concepts in a structured way through interactive practice problems and feedback on their answers.
The document discusses various object-oriented programming concepts in C#, including abstraction, encapsulation, inheritance, polymorphism, interfaces, abstract classes, virtual methods, classes, sealed classes, and provides code examples for foreach loops, switch statements, arrays, data types, boxing and unboxing, overloading and overriding, interfaces, classes vs. structures, access modifiers, abstract classes, and sealed classes.
This document provides an introduction to creating and using classes in C#. Key points covered include defining classes with fields, methods, and constructors; using accessibility modifiers like public and private; calling methods and using the this keyword; creating static methods; and using listboxes, comboboxes, and events for selection changes. Examples are provided for defining classes, constructors, static and instance methods, and populating and accessing selection properties of list and combo boxes.
18CSS101J PROGRAMMING FOR PROBLEM SOLVINGGOWSIKRAJAP
油
The document discusses various operators, control statements, and arrays in C programming. It begins by explaining operator precedence and types of operators such as relational, logical, increment, assignment etc. It then covers control statements including if-else, switch case, for, while, do-while loops. It also discusses goto, break and continue statements. Finally, it describes arrays including initialization, declaration, accessing elements and array operations. The document provides examples to explain the concepts in detail.
This document discusses exception handling in .NET. It defines exceptions as objects that are thrown when errors or unexpected events occur during program execution. Exceptions allow errors to be handled at multiple levels through try-catch blocks. The core exception class is System.Exception, which other custom exceptions inherit from. Exceptions can be thrown manually with throw or occur automatically from errors. Finally blocks ensure code is always executed even if an exception is thrown.
The document discusses classes, methods, and objects in C#. It explains that classes define methods and properties, and methods perform actions and can take parameters and return values. It provides examples of commonly used methods in classes like Console, Math, and Random. It also discusses how to define classes with data members and methods, and how to create objects from classes which allows calling instance methods on those objects. Classes serve both as program modules containing static methods and data, and as blueprints for generating objects with their own state and behavior.
The document discusses various C# programming concepts related to core C# and object-oriented programming, including parameter passing in C#, value types vs reference types, structs, enums, arrays, access modifiers, constructors, and properties. It provides code examples to demonstrate these concepts.
This document provides an overview of the C++ programming language. It discusses key C++ concepts like classes, objects, functions, and data types. Some key points:
- C++ is an object-oriented language that is an extension of C with additional features like classes and inheritance.
- Classes allow programmers to combine data and functions to model real-world entities. Objects are instances of classes.
- The document defines common C++ terms like keywords, identifiers, constants, and operators. It also provides examples of basic programs.
- Functions are described as modular and reusable blocks of code. Parameter passing techniques like pass-by-value and pass-by-reference are covered.
- Other concepts covered include
The document discusses arrays, strings, and functions in C programming. It begins by explaining how to initialize and access 2D arrays, including examples to take input from the user and store it in a 2D array. It then discusses initializing and accessing multidimensional arrays. Next, it covers array contiguous memory and the advantages and limitations of arrays. Finally, it discusses common programming errors related to array construction for real-time applications.
In this chapter we are going to get familiar with recursion and its applications. Recursion represents a powerful programming technique in which a method makes a call to itself from within its own method body. By means of recursion we can solve complicated combinatorial problems, in which we can easily exhaust different combinatorial configurations, e.g. generating permutations and variations and simulating nested loops. We are going to demonstrate many examples of correct and incorrect usage of recursion and convince you how useful it can be.
In this chapter we will discuss exceptions in the object-oriented programming and in Java in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct.
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
油
The document summarizes key topics related to recursion, pointers, and dynamic memory management in C programming:
Recursion is introduced as a process where a function calls itself repeatedly to solve a problem. Examples of recursive functions like factorial, Fibonacci series, and Towers of Hanoi are provided.
Pointers are defined as variables that store the memory addresses of other variables. Pointer operations like incrementing, decrementing, and arithmetic are described. The use of pointers to pass arguments to functions and access array elements is also demonstrated.
Dynamic memory allocation functions malloc(), calloc(), and realloc() are explained along with examples. These functions allocate and manage memory during run-time in C programs.
Object Oriented Programming using C++ Part IIIAjit Nayak
油
The document discusses inheritance in object-oriented programming. It defines inheritance as a technique where a new subclass inherits attributes and behaviors from an existing superclass without needing to redefine them. This allows code reuse and reduces development costs. The document provides examples of single inheritance with classes like Employee and Manager, and multi-level inheritance with Student, Test, and Result classes. It also discusses polymorphism through method overriding and different types of inheritance like public, private and protected.
Esoft Metro Campus - Diploma in Information Technology - (Module IX) Programming with C#.NET
(Template - Virtusa Corporate)
Contents:
Introduction to .NET Framework
.NET Framework Platform Architecture
Microsoft Visual Studio
C# Language
C#, VS and .NET Framework Versions
Your First C# Application
Printing Statements
Comments in C#
Common Type System
Value Types and Reference Type
Variables Declaration in C#
Type Conversion
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
If Statement
If Else Statement
If Else if Else Statement
Nested If Statement
Switch Statement
While Loop
Do While Loop
For Loop
Arrays
Accessing Arrays using foreach Loop
Two Dimensional Arrays
Classes and Objects in C#
Inheritance in C#
Partial Classes
Namespaces
Windows Forms Applications
Using Buttons, Labels and Text Boxes
Displaying Message Boxes
Error Handling with Try Catch finally
Using Radio Buttons
Using Check Boxes
Using List Boxes
Creating Menus
Creating ToolStrips
MDI Forms
Database Application in C#
Creating a Simple Database Application
SQL Insert / Update / Retrieving / Delete
SQL Command Execute Methods
Data Sets
The document discusses exception handling in C# programs. It explains that exceptions are errors that occur during program execution. The C# try, catch, and finally keywords are used to handle exceptions. The try block contains code that might cause exceptions. The catch block handles specific exception types. The finally block contains cleanup code that always executes. Built-in exceptions like DivideByZeroException are part of the .NET Framework. Exception handling prevents program crashes and allows graceful handling of errors.
The document discusses classes and methods in C#. It defines a class as a blueprint for creating objects with common properties and methods. A class declaration defines the data members (fields) and function members (methods) of the class. Methods are functions defined within a class that can access and modify the class's fields and other methods. The document covers various ways of passing parameters to methods, including value parameters, reference parameters, output parameters, and parameter arrays. It provides examples of defining classes with fields and methods, as well as invoking methods and passing parameters.
The document discusses call by value vs call by reference in functions, and different storage classes in C including auto, extern, register, and static. It provides examples of each storage class and how they determine the scope and lifetime of variables. It also discusses recursion and provides examples of recursive functions to calculate factorial, sum of natural numbers, Fibonacci series, and solve the Towers of Hanoi problem.
The document discusses control statements in C# programming. It describes selection statements like if, if-else, switch-case that are used to change the flow of program execution. It also covers iterative statements like while, do-while and for loops that are used to repeat blocks of code. Examples are provided to demonstrate nested if statements, stacking if statements, reversing a number using while loop, counting digits in a number, and calculating average of numbers entered by user.
In this chapter we will get more familiar with what methods are and why we need to use them. The reader will be shown how to declare methods, what parameters are and what a methods signature is, how to call a method, how to pass arguments of methods and how methods return values. At the end of this chapter we will know how to create our own method and how to use (invoke) it whenever necessary. Eventually, we will suggest some good practices in working with methods. The content of this chapter accompanied by detailed examples and exercises that will help the reader practice the learned material.
The document describes a program with 6 functions to help elementary school students learn math. The functions include easy and hard addition, subtraction, a grade converter, and a letter grade function. Each function is defined to perform a specific math operation or conversion, such as adding two numbers or converting a percentage to a letter grade. The program is intended to help students learn math concepts in a structured way through interactive practice problems and feedback on their answers.
The document contains multiple repeated links to a CNN Money article from 2008 about the financial crisis. It also includes links to unrelated websites about presentation slides and training. The high level information provided is minimal, consisting primarily of repeated identical links to the same source article.
Wonderful World - Road trip to Perth, Australia 2007Mark Normand
油
The document is the lyrics to Louis Armstrong's song "What a Wonderful World" from his 2007 album recorded during a trip to Australia. The lyrics describe the singer observing the natural beauty of the world from trees and roses to skies and rainbows as well as human interactions and babies growing up as he thinks to himself about what a wonderful world it is.
The document discusses interfaces in Java. It defines an interface as a syntactically similar to a class but lacking instance variables and having methods declared without bodies. Interfaces are defined using the interface keyword. A class implements an interface by providing implementations for all the interface's methods. Variables can be declared with an interface type and refer to any class that implements the interface, allowing polymorphic calls through interfaces.
The document discusses various C# object-oriented programming concepts including classes, structs, class members, passing values by value and reference, method overloading, constructors, static constructors, read-only fields, partial classes, static classes, and the Object class. It provides examples of declaring classes and structs, defining class members like fields, properties, methods, and constructors. It also covers passing parameters, calling constructors from other constructors, readonly fields, and anonymous types.
The document discusses events, creating custom events, and processing event streams in F#. It provides an overview of events, how they allow objects to communicate asynchronously, and how to create and handle events through the Event class. It also covers creating custom events for a Worker class to notify when the name or shift changes, attaching callback functions to event handlers, and an example of implementing an interface using events.
The document discusses object-oriented programming concepts in C#, including classes, constructors, destructors, and access modifiers. It provides examples of how to define classes with properties, methods, and constructors. It also explains the differences between public, private, and protected access modifiers and how they control accessibility of class members both within and outside of a class. The document contains code examples demonstrating the usage of classes, constructors, and access modifiers in C#.
1. The document discusses abstract data types (ADTs) and how they are represented by classes in C++. It provides examples of ADT specifications and how classes define the public interface and encapsulate private data.
2. The concepts of encapsulation, inheritance, polymorphism are explained. Operator overloading and friend functions are demonstrated with examples for a Point class.
3. Guidelines are given for organizing code into header and implementation files and compiling them, along with instructions for an upcoming quiz.
This lab report summarizes an experiment on conditional operators, nested loops, and goto statements in C programming. It includes examples of using conditional operators to check student results, nested for loops to print a pattern of numbers, and the goto statement to repeat a number input. The report concludes the experiment taught important programming concepts like decision making and loop control flow. Homework problems provide additional examples of half pyramids, largest number comparisons, and nested loop patterns.
The document discusses new features introduced in Java 8, including lambda expressions, functional interfaces, default and static methods in interfaces, and predefined functional interfaces like Predicate, Function, Consumer, and Supplier. It also covers stream API concepts like filtering, mapping, and processing streams using methods like collect(), count(), sorted(), min(), max(), forEach(), and toArray(). Stream API allows processing collections in a declarative way using lambda expressions and method references.
A Java method is a collection of statements that are grouped together to perform an operation. Methods can be created to take parameters and return values, and methods can be overloaded when multiple methods have the same name but different parameters. The this keyword refers to the current instance of a class and is used to differentiate between instance variables and local variables, or to call another constructor.
The document discusses defining programmer-defined classes in Java. It provides examples of defining a Bicycle class with data members and methods, creating multiple Bicycle objects, and using the Bicycle class in another class. It also covers concepts like visibility modifiers, constants, local variables, and passing objects to methods.
The document discusses defining programmer-defined classes in Java. It provides an example of defining a Bicycle class with data members and methods, and using it to track bicycle ownership. It then expands on this example by defining an Account class and using both classes in a sample program. The key aspects covered include defining classes, using visibility modifiers, passing objects to methods, and differentiating local variables from data members and parameters.
Namespace defines a scope for identifiers used in a program. Reference variables provide an alias for previously defined variables, and their main purpose is passing arguments to functions. C++ defines new and delete operators for allocating and freeing memory. The main() cannot directly access private data members; they must use member functions. A private member function can only be called by another member function of its class. A static member function can be called using the class name as class-name::function-name.
The document discusses Scala concepts including higher-order functions, anonymous functions, currying, tail recursion, classes and objects, properties with getters and setters, object-private fields, auxiliary constructors, primary constructors, nested classes, and singleton objects. It provides code examples to illustrate these Scala features and explains how they work and how they compare to similar concepts in other languages like Java. The document is intended as a lesson on these Scala programming concepts.
Java 8 introduced several new features including lambda expressions, functional interfaces, and streams to support functional programming. Interfaces can now contain default and static methods to allow multiple inheritance. Streams provide a way to process collections of data elements sequentially and support parallel processing.
Java 8 introduced several new features including lambda expressions, which allow functional-style programming in Java through functional interfaces containing a single abstract method, streams, which provide a way to process collections of objects in a declarative way, and default and static methods in interfaces to enable multiple inheritance. The document provides examples of using these new Java 8 features such as lambda expressions, functional interfaces, streams, and default and static methods in interfaces.
An index is identified by its signature, while a property is identified by its name. An indexer is always an instance member, but a property can be static. An indexer is accessed through element access, while a property is accessed through member access. Extension methods allow custom functions to be added to existing types through static classes and a new syntax. Events allow classes to notify other classes when something happens by invoking event handler methods. Abstract classes can have both abstract and concrete members, while interfaces only contain implicitly abstract members that must be implemented in derived classes.
The document discusses function overloading in C++ and provides an example program to calculate the area of different shapes using function overloading. It then discusses constructors and destructors with examples and explains polymorphism with an example. Next, it discusses different types of inheritance in C++ and provides an example program to implement operator overloading for a distance class. It also discusses virtual functions with an example and access specifiers in classes. Finally, it provides examples to define a student class, implement quicksort using templates and overloading relational operators.
The document discusses various C++ concepts including static class members, the this pointer, friend functions and classes, dynamic memory management using new and delete operators, function overloading, operator overloading, templates, and inheritance. Static class members are accessible to all objects of the class and only one copy is created for the entire class. The this pointer refers to the current object from within non-static member functions. Friend functions and classes can access private members of other classes. Dynamic memory is allocated using new and freed using delete.
5. Parameters Passing Pass by value Value types are passed by value by default 1- 息Masoud Milani int Smallest(int a, int b) { if (a > b) return b; else return a; } Change in a value parameter is not reflected in the caller
6. Parameters Passing Pass by reference out (output) 1- 息Masoud Milani void Smaller(int a, int b, out int result) { result=a>b?b: a; } Change in a out parameter is reflected in the caller The function can not use the value of an out parameter before an assignment is made to it. int a=20; int b=30; Smaller(a, b, out sm); sm=20
7. Parameters Passing Pass by reference ref (input and output) 1- 息Masoud Milani void Swap(ref int a, ref int b) { int t=a; a=b; b=t; } Change in a ref parameter is reflected in the caller The function can use the value of a reference parameter before an assignment is made to it. int a=20; int b=30; Swap(ref a, ref b); a=30 b=20
8. Parameters Passing Reference types are passed by reference by default 1- 息Masoud Milani public class ParamClass { public int myValue; } ParamClass p=new ParamClass(); p.myValue=9; Console.WriteLine("Before Increment, p.myValue={0}", p.myValue); Increment(p); Console.WriteLine("After Increment, p.myValue={0}", p.myValue); static void Increment(ParamClass q) { q.myValue++; } Before Increment, p.myValue=9 After Increment, p.myValue=10
9. Variable Number of Parameters 1- 息Masoud Milani int a=Smallest(5, 4, -3, 45, 2); int b=Smallest(1, 2, 3); int Smallest(params int[] a) { int smallest=int.MaxValue; foreach (int x in a) if (x < smallest) smallest=x; return smallest; }
10. Method Overloading More than one method with the same name can be defined for the same class methods must have different signatures 1- 息Masoud Milani
11. Operator Overloading More than one operator with the same name can be defined for the same class Overloaded operators must be public Static Precedence and associativity of the operators can not be changed. 1- 息Masoud Milani
12. Operator Overloading 1- 息Masoud Milani public class MyType { public MyType(int v) { myValue=v; } public int myValue; public static MyType operator + (MyType x, MyType y) { return new MyType(x.myValue + y.myValue); } } MyType p(5); MyType q(6); MyType s=p+q; s += p;
13. Operator Overloading 1- 息Masoud Milani public class MyType { public static MyType operator + (MyType x, int y) { return new MyType(x.myValue + y); } } MyType p(5); MyType s=p+7; s += 7
14. Operator Overloading 1- 息Masoud Milani public class MyType { public static MyType operator ++ (MyType x) { x.myValue += 1; return new MyType(x.myValue + 1); } } MyType p(5); MyType s=p++;
15. Operator Overloading 1- 息Masoud Milani public class MyType { public static bool operator true(MyType x) { return x.myValue !=0; } public static bool operator false (MyType x) { return x.myValue == 0; } } MyType z(5); if (z) Console.WriteLine("true"); else Console.WriteLine("false");
16. Indexers Indexers are properties that allow objects to be accessed like arrays The accessor functions for indexers take additional parameter(s) for index Indexers can not be declared static 1- 息Masoud Milani Exams ex=new Exams(); ex [1] =100; Indexer
17. Indexer 1- 息Masoud Milani public class Exams { public int this[int examNo] { get { } set { } } Exams ex=new Exams(); ex[1]=100; ex[2]=50; int average=ex[1] + ex[2];
18. Example using System; /// <summary> ///油油油油 A simple indexer example. /// </summary> class IntIndexer { 油油油 private string[] myData; 油油油 public IntIndexer(int size) 油油油 { 油油油油油油油 myData = new string[size]; 油油油油油油油 for (int i=0; i < size; i++) 油油油油油油油 { 油油油油油油油油油油油 myData[i] = "empty"; 油油油油油油油 } 油油油 } 油油油 1- 息Masoud Milani
19. Example public string this[int pos] 油油油 { 油油油油油油油 get 油油油油油油 { 油油油油油油油油油油油 return myData[pos]; 油油油油油油油 } 油油油油油油油 set 油油油油油油 { 油油油油油油油油油油油 myData[pos] = value; 油油油油油油油 } 油油油 } 油油油 1- 息Masoud Milani Should use this keyword
20. Example static void Main(string[] args) 油油油 { 油油油油油油油 int size = 10; 油油油油油油油 IntIndexer myInd = new IntIndexer(size); 油油油油油油油 myInd[9] = "Some Value"; 油油油油油油油 myInd[3] = "Another Value"; 油油油油油油油 myInd[5] = "Any Value"; 油油油油油油油 Console.WriteLine("\nIndexer Output\n"); 油油油油油油油 for (int i=0; i < size; i++) 油油油油油油油 { 油油油油油油油油油油油 Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]); 油油油油油油油 } 油油油 } } 1- 息Masoud Milani
21. Output Indexer Output myInd[0]: empty myInd[1]: empty myInd[2]: empty myInd[3]: Another Value myInd[4]: empty myInd[5]: Any Value myInd[6]: empty myInd[7]: empty myInd[8]: empty myInd[9]: Some Value 1- 息Masoud Milani
22. Exercise Write a class Exams that have 3 private integer fields exam1, exam2 and exam3 An indexer that sets or gets the value of each exam A public property Average that returns the average of the three exams 1- 息Masoud Milani
23. Exams class 1- 息Masoud Milani public class Exams { public Exams(int ex1, int ex2, int ex3) { } private int exam1; private int exam2; private int exam3; public double Average { } }
24. Inheritance Implements isA relation Student isA Person 1- 息Masoud Milani public class Person { public Person(string fn, string ln) { firstName=fn; lastName=ln; } private string firstName; private string lastName; } public class Student : Person { public Student(string fn, string ln, string mj): base(fn, ln) { major=mj; } private string major; }
25. Inheritance A subclass can hide the inherited members of its superclass using the keyword new 1- 息Masoud Milani public class Person { public void Show() { Console.Write("Name: {0}, {1}", lastName, firstName)} } public class Student : Person { public new void Show() { base.Show(); Console.Write("major: {0}", major); } }
27. Virtual Function A class can allow its subclasses to override its member functions by declaring them virtual 1- 息Masoud Milani public class Person { public virtual void Show() { Console.Write("Name: {0}, {1}", lastName, firstName)} } public class Student : Inheritance.Person { public override void Show() { base.Show(); Console.Write("major: {0}", major); } } using namespace the override keyword is also required.
28. Virtual Function 1- 息Masoud Milani Person p = new Person("P1-F", "P1-L"); p.Show(); Console.WriteLine(); Student s=new Student("S1-F", "S1-L", "CS"); s.Show(); Console.WriteLine(); p=s; p.Show(); Name: S1-L, S1-F Major: CS Name: S1-L, S1-F Major: CS Name: P1-L, P1-F
29. Sealed Modifier A sealed class is a class that can not be the base of any other class used to prevent inheritance from the class to facilitate future class modification A sealed method overrides an inherited virtual method with the same signature Used to prevent further overriding of the method 1- 息Masoud Milani
30. Example using System; sealed class MyClass { public int x; public int y; } class MainClass { public static void Main() { MyClass mC = new MyClass(); mC.x = 110; mC.y = 150; Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); } } 1- 息Masoud Milani
32. Abstract Classes An abstract class is a class that can not be instantiated Abstract classes are used for reuse and structural organization of the program Abstract classes can have abstract or specified methods Non-abstract subclasses must override the abstract methods that they inherit 1- 息Masoud Milani
33. Abstract Classes Software requirement is given: There is no object that is only a person. Each person is either a student or a graduate student 1- 息Masoud Milani
34. Abstract Classes 1- 息Masoud Milani public abstract class Person { public Person(string fn, string ln) { firstName=fn; lastName=ln; } private string firstName; private string lastName; public virtual void Show() { Console.Write("Name: {0}, {1}", lastName, firstName); } } Error: Abstract classes can not be instantiated Person p(FN-1, LN-1);
35. Exercise 1- 息Masoud Milani Courses exam1 exam2 exam3 Average takes Class Grad Student GradStudent( ) bool pass // >80 void override Show() class Student string major double Average Student( ) bool Pass // >60 void override Show() Abstract class Person string fName string lName Person(string fn, string ln) void virtual Show() isA isA
36. Exercise Ask the number of students For each student ask First Name Last Name Major Scores for each of three exams Whether or not this is a graduate student Create an appropriate student object and store it in an array Call Show member of each array entry 1- 息Masoud Milani
37. Person class 1- 息Masoud Milani public abstract class Person { public Person(string fn, string ln) { } private string firstName; private string lastName; public virtual void Show() { } }
38. Student class 1- 息Masoud Milani public class Student : Inheritance.Person { public Student(string fn, string ln, string mj, int ex1, int ex2, int ex3):base(fn, ln) { } private string major; public override void Show() { } public virtual bool Pass { get { } } protected Exams scores; public double Average { get { } } }
39. GradStudent class 1- 息Masoud Milani public class GradStudent : Inheritance.Student { public GradStudent(string fn, string ln, string mj, int ex1, int ex2, int ex3): base(fn, ln, mj, ex1, ex2, ex3) { } public override bool Pass { get { } } }
40. Files A file is a sequential sequence of bytes Applicable classes Text Input StreamReader Text Output StreamWriter Input/Output FileStream NameSpace System.IO 1- 息Masoud Milani
42. StreamReader Similar to StreamWriter Check for end of stream using the method Peek() 1- 息Masoud Milani StreamReader inpTextFile=new StreamReader("myOutFile.txt"); while(inpTextFile.Peek() >=0) { string nextLine=inpTextFile.ReadLine(); Console.WriteLine(int.Parse(nextLine.Substring(nextLine.IndexOf("=")+1))); } inpTextFile.Close();
43. Exercise Modify the previous program to save and retrieve information 1- 息Masoud Milani
44. FileStream To open a FileStream, we need to specify Physical path File Mode File Access 1- 息Masoud Milani
45. FileMode Enumeration Append Opens the file if it exists and seeks to the end of the file, or creates a new file Create A new file should be created. If the file already exists, it will be overwritten. Open An existing file should be opened 1- 息Masoud Milani
47. Formatter Direct reading to and Writing from FileStreams is very difficult Must read and write byte by byte Use a formatter to format objects that are to be written to the FileStream BinaryFormatter Formats objects in binary 1- 息Masoud Milani
52. Exercise Modify the previous program to save and retrieve information using a Binary Formatter 1- 息Masoud Milani
53. Exception Handling Exceptions are raised when a program encounters an illegal computation Division by zero Array index out of range Read beyond end of file . 1- 息Masoud Milani
54. Exception Handling A method that is unable to perform a computation throws an exception object Exceptions can be caught by appropriate routines called exception handlers Exception handlers receive the exception object containing information regarding the error Exception objects are instances of classes that are derived from Exception class 1- 息Masoud Milani
55. Exception Handling try statement allows for catching exceptions in a block of code try statement has one or more catch clauses to catch exceptions that are raised in the protected block 1- 息Masoud Milani int[] a= new int[20]; try { Console.WriteLine(a[20]); } catch (Exception e) { Console.WriteLine(e.Message); } Index was outside the bounds of the array
56. Exception Handling A try block can have multiple catch clauses The catch clauses are searched to find the first clause with a parameter that matches the thrown exception The program continues execution with the first statement that follows the try-catch-finally construct 1- 息Masoud Milani
57. Exception Handling try statement has an optional finally clause that executes When an exception is thrown and the corresponding catch clause is executed When the protected block executes without raising throwing exception 1- 息Masoud Milani
58. Exception Handling 1- 息Masoud Milani int[] a= new int[20]; try { Console.WriteLine(a[2]); } catch (Exception e) { Console.WriteLine(e.Message); } finally { Console.WriteLine(Finally we are done!"); } Finally we are done!
59. Exception Handling Exception classes IndexOutOfRangeException Class油 when an attempt is made to access an element of an array with an index that is outside the bounds of the array. This class cannot be inherited DivideByZeroException Class The exception that is thrown when there is an attempt to divide an integral or decimal value by zero. 1- 息Masoud Milani
60. Exception Handling Exception classes InvalidCastException Class The exception that is thrown for invalid casting or explicit conversion EndOfStreamException Class The exception that is thrown when reading is attempted past the end of a stream For a list of Exception classes search for SystemException Hierarchy in MSDN.Net 1- 息Masoud Milani
61. Programmer Defined Exceptions Programmer defined exception classes must inherit from ApplicationException class Provide at least one constructor to set the message property 1- 息Masoud Milani public class MyException : System.ApplicationException { public MyException(string message):base(message) { } }
62. Programmer Defined Exceptions 1- 息Masoud Milani public static int g(int a, int b) { // adds positive numbers if (a <0) { MyException e=new MyException("1st parameter is negative"); throw(e); } if (b <0) { MyException e=new MyException("2nd dparameter is negative"); throw(e); } return a+b; } try { Console.WriteLine("g(4, -5)={0}", g(4, -5)); } catch (Exception e) Console.WriteLine(e.Message); }
63. Delegates A delegate is a class that has only one or more methods Allows methods to be treated like objects 1- 息Masoud Milani delegate int D1(int i, int j);
64. Delegates 1- 息Masoud Milani delegate int D1(int i, int j); public static int add(int a, int b) { Console.WriteLine(a+b); return a+b; } public static int mult(int a, int b) { Console.WriteLine(a*b); return a*b } static void Main(string[] args) { D1 d1=new D1(add); D1 d2=new D1(mult); d1=d1 + d2; d1(5, 5); } 10 25
65. Delegates 1- 息Masoud Milani delegate int D1(int i, int j); public static int add(int a, int b) { Console.WriteLine(a+b); return a+b; } public static int mult(int a, int b) { Console.WriteLine(a*b); return a*b } static void Main(string[] args) { D1 d1=new D1(add); D1 d2=new D1(mult); d1=d1 + d2; f(d1); } 10 25 public static void f(D1 d) { d(5,5); }
66. Exercise Write a sort method that accepts an array of integer and a boolean delegate, compare, and sorts the array according to the delegate 1- 息Masoud Milani public static void sort(int[] data, CompareDelegate Compare) { for (int i=0; i<data.Length; ++i) for(int j=i+1; j<data.Length; j++) if (Compare(data[i],data[j])) { int t=data[i]; data[i]=data[j]; data[j]=t; } }
67. Interfaces An interface specifies the members that must be provided by classes that implement them An Interface can define methods, properties, events, and indexers The interface itself does not provide implementations for the members that it defines 1- 息Masoud Milani
68. Interfaces To add an interface, add a class and change it in the editor 1- 息Masoud Milani interface IPublication { string Title { get; set; } string Publisher { get; set; } void Display(); }
69. Interfaces 1- 息Masoud Milani public class Book: IPublication { public Book(string title, string author, string publisher) { Title=title; Author=author; Publisher=publisher; } private string author; private string title; private string publisher; public string Author { } public string Title { } public string Publisher { } public void Display() { } }
70. Interfaces 1- 息Masoud Milani static public void Display(IPublication[] p) { for (int i=0; i<p.Length; ++i) p[i].Display(); } static void Main(string[] args) { IPublication[] publications= new IPublication[2]; publications[0] = new Book ("t0", "a0", "p0"); publications[1] = new Magazine ("t1", "a1"); Display(publications); } public class Magazine : Interfaces.IPublication { }
71. Interfaces An interface can have only public members A class that is implementing an interface must implement all its members A class can implement multiple interfaces 1- 息Masoud Milani