How to work with indexers, delegates, events, and operators

Slides:



Advertisements
Similar presentations
Lists, Loops, Validation, and More
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Chapter 15 Strings String::Concat String::CompareTo, Equals, == If( string1 == S”Hello”) String1->Equals(S”Hello”) String1->CompareTo(S”Hello”) CompareTo.
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modularizing Your Code with Methods.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections.
The Java Programming Language
Parameters. Overview A Reminder Why Parameters are Needed How Parameters Work Value Parameters Reference Parameters Out Parameters.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Neal Stublen What’s an indexer?  An array has an indexer… int[] myArray = new int[5]; for (int index = 0; index < 5; ++index) {
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Arrays Chapter 7.
Chapter VII: Arrays.
© 2016, Mike Murach & Associates, Inc.
INF230 Basics in C# Programming
Java Language Basics.
Chapter 7 User-Defined Methods.
Lecture 14 Throwing Custom Exceptions
Chapter 10 – Exception Handling
Java Programming Language
Methods Attributes Method Modifiers ‘static’
Why exception handling in C++?
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Computing with C# and the .NET Framework
How to Create and use Classes and Structures
Advanced Programming in Java
Chapter 14: Exception Handling
How to work with indexers, delegates, events, and operators
CS 302 Week 11 Jim Williams, PhD.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
String Objects & its Methods
The relational operators
Lecture 11 C Parameters Richard Gesick.
Java Programming Language
Variables ICS2O.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Group Status Project Status.
Delegates & Events 1.
PHP.
Part B – Structured Exception Handling
Object Oriented Programming in java
How to Create and use Classes and Structures
Exception Handling in Java
Tonga Institute of Higher Education
Chapter 13 Exception Handling: A Deeper Look
How to organize and document your classes
Microsoft Visual Basic 2005 BASICS
CIS 199 Final Review.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Special instance methods: toString
Introduction to Programming
Based on Murach (ch 14) and Deitel 2012
Barb Ericson Georgia Institute of Technology Oct 2005
Events, Delegates, and Lambdas
Presentation transcript:

How to work with indexers, delegates, events, and operators Based on Murach (ch 13) and Deitel

Objectives Applied Develop and use classes that have indexers delegates events overloaded operators Knowledge Describe the use of an indexer. Explain why you should validate parameters and throw exceptions in your classes. Describe the use of delegates and events without and with anonymous methods and lambda expressions. Describe the use of operator overloading.

The code for a simple ProductList class (just an idea, based on Product class ch.12) public class ProductList { private List<Product> products; public ProductList() products = new List<Product>(); } public int Count => products.Count; public void Add(Product product) products.Add(product); public void Add(string code, string description, decimal price) Product p = new Product(code, description, price); products.Add(p); PROPERTY: Count of List Gets the number of elements contained in the System.Collections.Generic.List. Returns: The number of elements contained in the System.Collections.Generic.List. overloaded

Calls methods from another class ProductDB The code for a simple ProductList class (just an idea, based on Product class ch.12 cont) public Product GetProductByIndex(int i) => products[i]; public void Remove(Product product) { products.Remove(product); } public void Fill() => products = ProductDB.GetProducts(); public void Save() => ProductDB.SaveProducts(products); Calls methods from another class ProductDB

ProductList class

ProductList class cont.

An indexer that uses an integer as an index Indexer is a special property private List<Product> products; //cannot access directly, private   public Product this[int i] { get return products[i]; //no validation yet } set products[i] = value;

A read-only indexer that uses a string as an index public Product this[string code] { get foreach (Product p in products) if (p.Code == code) return p; } return null; //not found

A read-only indexer with an expression body (no “set”) public Product this[int i] => products[i];

Using these indexers First: Populating list ProductList products = new ProductList(); products.Add("CS15", "Murach's C# 2015", 56.50m); Accessing from list Product p1 = products[0]; //using position Product p2 = products["CS15"]; //code products[i] = new Product(code, description, price); public Product this[int i] { get{return products[i];} set{products[i] = value;} }

An indexer that checks the range and throws an argument exception public Product this[int i] { get if (i < 0 || i >= products.Count) throw new ArgumentOutOfRangeException(i.ToString()); } return products[i]; ...

An indexer that validates data and throws an argument exception public Product this[string code] { get if (code.Length > 4) throw new ArgumentException( "Maximum length of Code is 4 characters."); } foreach (Product p in products) //if code is valid search until found if (p.Code == code) return p; return null; //if NOT found

Three argument exceptions Description ArgumentOutOfRangeException(message) Use when the value is outside the acceptable range of values. ArgumentNullException(message) Use when the value is null and a null value is not allowed. ArgumentException(message) Use when the value is invalid for any other reason.

Review: Terminology*

Exception Keywords*

Running example* namespace UsingExceptions { class Program using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UsingExceptions { class Program static void Main(string[] args) int x = 10; int y = 5; int result; try result = x / y; Console.WriteLine("The result is: {0}", result); } catch Console.WriteLine("An error occurred! Better check the code!"); finally Console.WriteLine("Just proving that this code always runs."); Console.ReadLine(); }}}

Catching Specific Exceptions

Exceptions Hierarchy try { result = x / y; Console.WriteLine("The result is: {0}", result); } catch (System.DivideByZeroException e) Console.WriteLine("Whoops! You tried to divide by zero!"); Console.WriteLine(e.Message); catch (System.ArithmeticException e)

More Specific Exceptions -> First. Try this * { result = x / y; Console.WriteLine("The result is: {0}", result); } catch (System.ArithmeticException e) Console.WriteLine("Whoops! You tried to divide by zero!"); Console.WriteLine(e.Message); catch (System.DivideByZeroException e) finally Console.WriteLine("Just proving that this code always runs."); Console.ReadLine();

Exceptions are Objects http://msdn.microsoft.com/en-us/library/system.systemexception.aspx System.Exception System.ApplicationException (non fatal exceptions) http://msdn.microsoft.com/en-us/library/system.applicationexception.aspx

Custom Exceptions

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CustomExceptions { public class MyOwnException : Exception public MyOwnException() : base("Sergey is not welcomed here!") //Exception(string) //this.HelpLink = "http://msdn.microsoft.com/en- us/library/system.exception.aspx"; } class Program static string GetName() string s = Console.ReadLine(); if (s.Equals("Sergey")) throw new MyOwnException(); return s;

static void Main(string[] args) { string theName; try theName = GetName(); Console.WriteLine("Hello {0}", theName); } catch (MyOwnException nje) Console.WriteLine(nje.Message); Console.WriteLine("For help, visit: {0}", nje.HelpLink); finally Console.WriteLine("Have a nice day!"); Console.ReadLine();

An if statement that validates data before setting a property value Product p = null; if (txtCode.Text.Length <= 4) { p = products[txtCode.Text]; } However, you still need to validate in ProductLists because you cannot count on others, especially if your class is reusable.

Delegates Overall it is similar (but smarter) to the old "C" function pointer, where functions can be assigned like a variable and called in the run time based on dynamic conditions. Type-safe function Delegate is defined with a specific signature (return type, parameter type and order etc). To invoke a delegate object, one or more methods are required with the EXACT same signature. A delegate object is first created similar like a class object created. The delegate object will hold a reference of a function. The function will then can be called via the delegate object. Commonly used for event handlers

Delegates cont. 1. Defining the delegate public delegate int Calculate (int value1, int value2); 2. Declare a variable that will hold a function of type Calculate private Calculate calculate; public static void Main() { // Assign the real function Add() to the variable Calculate calculate= Add; //can be Sub! // Call whatever function has been stored in the variable adderFunction int res = calculate( 1, 2 ); } // These functions matches EXACTLY the signature defined in the MathFunction type private int Add( int n1, int n2 ) return n1 + n2; private int Sub( int n1, int n2 ) return n1 - n2;

Ex.: Delegate. Very Basic namespace DelegateDemo { public delegate void HelloMethodDelegate(String msg); class Program static void Main(string[] args) //create instance of delegate, like ceate an object //instead of Hello("Hello World!"); HelloMethodDelegate helloDelegate = new HelloMethodDelegate(Hello); helloDelegate("Hello World!"); Console.Read(); } //matching signature of delegate //try chang void to string -> error, because type safe public static void Hello(String str) Console.WriteLine(str); >Hello World!

The syntax for declaring a delegate public delegate returnType DelegateName([parameterList]); Code that declares a delegate in the ProductList class public delegate void ChangeHandler(ProductList products);

Code in a form that uses the delegate (idea) public partial class frmProducts : Form { // create the delegate object and identify the method it uses ProductList.ChangeHandler myDelegate = new ProductList.ChangeHandler(PrintToConsole);   // a method with the same signature as the delegate private static void PrintToConsole(ProductList products) Console.WriteLine("The products list has changed!"); for (int i = 0; i < products.Count; i++) Product p = products[i]; Console.WriteLine(p.GetDisplayText("\t")); }

Code in a form that uses the delegate (idea) cont. private void frmProducts_Load(object sender, EventArgs e) { // create the argument that's required by the delegate ProductList products = new ProductList();   // add products to the product list products.Add("BJWN", "Murach's Beginning Java with NetBeans", 57.50m); products.Add("CS15", "Murach's C# 2015", 56.50m); // call the delegate and pass the required argument myDelegate(products); } } 

The syntax for declaring an event An event is a signal that a particular action has occurred on an object that’s created from the class. Classes using that object can response by wiring event handler to it. public event Delegate EventName; Code that declares and raises an event in the ProductList class public class ProductList { public delegate void ChangeHandler(ProductList products); public event ChangeHandler Changed; // declare the event   public void Add(Product product) products.Add(product); Changed(this); // raise the event } ...

Delegates and events 1. Define a delegate 2. Define an event based on that delegate 3. Raise the event May seem complex It is very flexible

Code in a form that wires the event handler and handles the event (idea) ProductList products = new ProductList();   private void frmProducts_Load(object sender, System.EventArgs e) { // wire the event to the method that handles the event products.Changed += new ProductList.ChangeHandler(PrintToConsole); ... } // the method that handles the event private void PrintToConsole(ProductList products) Console.WriteLine("The products list has changed!"); for (int i = 0; i < products.Count; i++) Product p = products[i]; Console.WriteLine(p.GetDisplayText("\t"));

Another way: How to create a delegate using an anonymous method (no name method) The same as printToConsole Ex.: ProductList.ChangeHandler myDelegate = delegate (ProductList products) { Console.WriteLine("The products list has changed!"); for (int i = 0; i < products.Count; i++) { ... } }; myDelegate(products); Ex.: using a lambda expression ProductList.ChangeHandler myDelegate = products =>

How wire an event using an anonymous method products.Changed += delegate (ProductList products) { Console.WriteLine("The products list has changed!"); for (int i = 0; i < products.Count; i++) { ... } }; How wire an event using a lambda expression products.Changed += products =>

Overloading operators C# defines meaning for built-in types (ex. +, ==) product1 == product2 (same Code, Description, Price) The syntax for overloading unary operators public static returnType operator unary-operator(type operand) Unary operators + - ! ++ -- true false Ex: +x, -x, !x The syntax for overloading binary operators public static returnType operator binary-operator(type-1 operand-1, type-2 operand-2) Binary operators + - * / % & | == != > < >= <=

The Equals method of the Object class Description Equals(object) Returns a Boolean value that indicates whether the current object refers to the same instance as the specified object. Equals(object1, object2) A static version of the Equals method that compares two objects to determine if they refer to the same instance. The GetHashCode method of the Object class Method Description GetHashCode() Returns an integer value that’s used to identify objects in a hash table. If you override the Equals method, you must also override the GetHashCode method.  

Part of a ProductList class that overloads the + operator public class ProductList { private List<Product> products; public void Add(Product p) products.Add(p); } public static ProductList operator + (ProductList pl, Product p) pl.Add(p); return pl; .

Code that uses the + operator of the ProductList class ProductList products = new ProductList(); Product p = new Product("CS15", "Murach's C# 2015", 56.50m); products = products + p; Another way to use the + operator products += p;

Code that uses an expression-bodied operator public ProductList Add(Product p) { products.Add(p); return this; } public static ProductList operator + ( ProductList pl, Product p) => pl.Add(p);

Code that overloads the == operator for a Product class (cont.) To handle null public static bool == (Product p1, Product p2) { if (Object.Equals(p1 == null) //both null if (Object.Equals(p2 == null) return true; else return false; //p1 is null, p2 is not return p1.Equals(p2); } public static bool != (Product p1, Product p2) return !(p1 == p2); If == is overloaded -> need to overload != If > is overloaded -> need to overload <

Code that overloads the == operator for a Product class (cont.) public override bool Equals(Object obj) { if (obj == null) //obviously return false; Product p = (Product)obj; if (this.Code == p.Code && this.Description == p.Description && this.Price == p.Price) return true; else }   public override int GetHashCode() string hashString = this.Code + this.Description + this.Price; return hashString.GetHashCode();

Code that uses the == operator of the Product class Product p1 = new Product("CS15", "Murach's C# 2015", 56.50m); Product p2 = new Product("CS15", "Murach's C# 2015", 56.50m); if (p1 == p2) // This evaluates to true. Without the // overloaded == operator, it would // evaluate to false (different objects).

The code for the Enhanced ProductMaintanace Behavior the same as in ch 12   Enhanced ProductList class Unchanged Products class Unchanged frmNewProduct class Changed frmProductMain class

The code for the Enhanced ProductMaintanace Behavior the same as in ch 12 Enhanced ProductList class public class ProductList { private List<Product> products; public delegate void ChangeHandler(ProductList products); public event ChangeHandler Changed; public ProductList() products = new List<Product>(); } public int Count => products.Count; Event raises when products list are changed

The code for the ProductList class (cont.) public Product this[int i] { get if (i < 0) throw new ArgumentOutOfRangeException("i"); } else if (i >= products.Count) return products[i]; set products[i] = value; Changed(this);

The code for the ProductList class (cont.) public Product this[string code] { get foreach (Product p in products) if (p.Code == code) return p; } return null; public void Fill() => products = ProductDB.GetProducts(); public void Save() => ProductDB.SaveProducts(products);

The code for the ProductList class (cont.) public void Add(Product product) { products.Add(product); Changed(this); } public void Add(string code, string description, decimal price) Product p = new Product(code, description, price); products.Add(p); public void Remove(Product product) products.Remove(product);

The code for the ProductList class (cont.) public static ProductList operator +(ProductList pl, Product p) { pl.Add(p); return pl; } public static ProductList operator - (ProductList pl, Product p) pl.Remove(p);

The code for the Product Maintenance form Instead of List<> it is ProductList Can utilize ProductList indexers Fill Method Save Method + Overloaded - Overloaded Changed event of products object In ProductList Changed event is raised any time a product is added or removed or changed in product list. Then the HandleChange method calls Save methods of products object and it call FillProductListBox to refresh the box.

The code for the Product Maintenance form private ProductList products = new ProductList(); private void frmProductMain_Load(object sender, EventArgs e) { products.Changed += new ProductList.ChangeHandler(HandleChange); products.Fill(); FillProductListBox(); } private void FillProductListBox() Product p; lstProducts.Items.Clear(); for (int i = 0; i < products.Count; i++) p = products[i]; lstProducts.Items.Add(p.GetDisplayText("\t"));

The code for the Product Maintenance form cont. private void btnAdd_Click(object sender, EventArgs e) { frmNewProduct newForm = new frmNewProduct(); Product product = newForm.GetNewProduct(); if (product != null) { products += product; } private void btnDelete_Click(object sender, EventArgs e) int i = lstProducts.SelectedIndex; if (i != -1) Product product = products[i]; string message = "Are you sure you want to delete " + product.Description + "?"; DialogResult button = MessageBox.Show(message, "Confirm Delete", MessageBoxButtons.YesNo); if (button == DialogResult.Yes) products -= product;

The code for the Product Maintenance form cont. private void btnExit_Click(object sender, EventArgs e) { this.Close(); } private void HandleChange(ProductList products) products.Save(); FillProductListBox();

Project 3-3 Direct a simple robot Create a form that lets the user move a simple robot a given direction and distance, and create a class that performs the robot movements.