[go: up one dir, main page]

0% found this document useful (0 votes)
108 views102 pages

Lecture05 - ITE 5230

Uploaded by

Madhav Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views102 pages

Lecture05 - ITE 5230

Uploaded by

Madhav Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

ITE 5230

Windows Application Development using C#.Net


Lecture 5

1
Chapter 12

How to create
and use classes

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 2
Objectives
Applied
1. Given the specifications for an application that uses classes with any
of the members presented in this chapter, develop the application
and its classes.
2. Use the Solution Explorer and the CodeLens feature to browse the
classes in a solution.
3. Use class diagrams and the Class Details window to review, delete,
and start the members of the classes in a solution.
4. Use the Peek Definition window to display and edit the code for a
member in another class from within the class that refers to it.
Knowledge
1. List and describe the three layers of a three-layered application.
2. Describe these members of a class: constructor, method, field, and
property.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 3
Objectives (cont.)
3. Describe the concept of encapsulation.
4. Explain how instantiation works.
5. Describe the main advantage of using object initializers.
6. Describe the concept of overloading a method.
7. Explain what a static member is.
8. Explain how auto-implemented properties work.
9. Explain how expression-bodied properties and methods work.
10. Describe the basic procedure for using the live code analysis feature
to generate code stubs.
11. Describe the difference between a class and a structure.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 4
The architecture of a three-layered application

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 5
The members of a Product class
Properties Description
Code A string that contains a code that
uniquely identifies each product.
Description A string that contains a description of
the product.
Price A decimal that contains the product’s
price.
Method Description
GetDisplayText(sep) Returns a string that contains the code,
description, and price in a displayable
format. The sep parameter is a string
that’s used to separate the elements.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 6
The members of a Product class (cont.)
Constructors Description
() Creates a Product object with
default values.
(code, description, price) Creates a Product object using
the specified code, description,
and price values.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 7
Types of class members
Member Description
Property Represents a data value associated with an object
instance.
Method An operation that can be performed by an object.
Constructor A special type of method that’s executed when an
object is instantiated.
Delegate A special type of object that’s used to pass a
method as an argument to other methods.
Event A signal that notifies other objects that something
noteworthy has occurred.
Field A variable that’s declared at the class level.
Constant A constant.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 8
Types of class members (cont.)
Member Description
Indexer A special type of property that allows individual
items within the class to be accessed by index
values. Used for classes that represent collections of
objects.
Operator A special type of method that’s performed for a C#
operator such as + or ==.
Class A class that’s defined within the class.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 9
Class and object concepts
 An object is a self-contained unit that has properties, methods,
and other members. A class contains the code that defines the
members of an object.
 An object is an instance of a class, and the process of creating an
object is called instantiation.
 Encapsulation is one of the fundamental concepts of object-
oriented programming. It lets you control the data and operations
within a class that are exposed to other classes.
 The data of a class is typically encapsulated within a class using
data hiding. In addition, the code that performs operations within
the class is encapsulated so it can be changed without changing
the way other classes use it.
 Although a class can have many different types of members, most
of the classes you create will have just properties, methods, and
constructors.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 10
The Product class: Fields and constructors
namespace ProductMaintenance
{
public class Product
{
private string code;
private string description;
private decimal price;

public Product(){}

public Product(string code, string description,


decimal price)
{
this.Code = code;
this.Description = description;
this.Price = price;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 11
The Product class: The Code property
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 12
The Product class: The Description property
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 13
The Product class: The Price property
public decimal Price
{
get
{
return price;
}
set
{
price = value;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 14
The Product class: The GetDisplayText method
public string GetDisplayText(string sep)
{
return code + sep + price.ToString("c") + sep +
description;
}
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 15
Two Product objects that have been instantiated
from the Product class
product1 product2
Code=CS15 Code=VB15
Description=Murach’s C# 2015 Description=Murach’s Visual Basic 2015
Price=56.50 Price=56.50

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 16
Code that creates these two object instances
Product product1, product2;
product1 = new Product("CS15", "Murach's C# 2015", 56.50m);
product2 = new Product("VB15", "Murach's Visual Basic 2015",
56.50m);

Code that creates the object instances


with object initializers
product1 = new Product { Code = "CS15",
Description = "Murach's C# 2015", Price = 56.50m };
product2 = new Product { Code = "VB15",
Description = "Murach's Visual Basic 2015", Price = 56.50m };

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 17
The dialog box for adding a class

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 18
The starting code for the new class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProductMaintenance
{
class Product
{
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 19
Examples of field declarations
private int quantity; // A private field
public decimal Price; // A public field
public readonly int Limit = 90; // A public read-only field

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 20
A Product class that uses public fields
public class Product
{
// Public fields
public string Code;
public string Description;
public decimal Price;

public Product()
{
}

public Product(string code, string description, decimal price)


{
this.Code = code;
this.Description = description;
this.Price = price;
}

public string GetDisplayText(string sep)


{
return Code + sep + Price.ToString("c") + sep + Description;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 21
The syntax for coding a public property
public type PropertyName
{
[get { get accessor code }]
[set { set accessor code }]
}

A read/write property
public string Code
{
get { return code; }
set { code = value; }
}

A read-only property
public decimal DiscountAmount
{
get
{
discountAmount = subtotal * discountPercent;
return discountAmount;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 22
A statement that sets a property value
product.Code = txtProductCode.Text;

A statement that gets a property value


string code = product.Code;

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 23
The syntax for coding a public method
public returnType MethodName([parameterList])
{
statements
}

A method that accepts parameters


public string GetDisplayText(string sep)
{
return code + sep + price.ToString("c") + sep
+ description;
}

An overloaded version of the method


public string GetDisplayText()
{
return code + ", " + price.ToString("c") + ", "
+ description;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 24
Statements that call the GetDisplayText method
lblProduct.Text = product.GetDisplayText("\t");
lblProduct.Text = product.GetDisplayText();

How the IntelliSense feature lists


overloaded methods

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 25
A constructor with no parameters
public Product()
{
}

A constructor with three parameters


public Product(string code, string description,
decimal price)
{
this.Code = code;
this.Description = description;
this.Price = price;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 26
A constructor with one parameter
public Product(string code)
{
Product p = ProductDB.GetProduct(code);
this.Code = p.Code;
this.Description = p.Description;
this.Price = p.Price;
}

Statements that call these constructors


Product product1 = new Product();
Product product2 = new Product("CS15",
"Murach's C# 2015", 56.50m);
Product product3 = new Product(txtCode.Text);

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 27
Default values for instance variables
Data type Default value
All numeric types 0
Boolean false
Char null
Object null
Date 12:00 a.m. on January 1, 0001

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 28
A class that contains static members
public static class Validator
{
private static string title = "Entry Error";

public static string Title


{
get
{
return title;
}
set
{
title = value;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 29
A class that contains static members (cont.)
public static bool IsPresent(TextBox textBox)
{
if (textBox.Text == "")
{
MessageBox.Show(textBox.Tag
+ " is a required field.", Title);
textBox.Focus();
return false;
}
return true;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 30
Code that uses static members
if ( Validator.IsPresent(txtCode) &&
Validator.IsPresent(txtDescription) &&
Validator.IsPresent(txtPrice) )
isValidData = true;
else
isValidData = false;

A using directive for the Validator class


using static ProductMaintenance.Validator;

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 31
The Product Maintenance form

The New Product form

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 32
The Tag property settings for the text boxes on the
New Product form
Control Tag property setting
txtCode Code
txtDescription Description
txtPrice Price

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 33
The Product class
Property Description
Code A string that contains a code that
uniquely identifies the product.
Description A string that contains a description of
the product.
Price A decimal that contains the product’s
price.
Method Description
GetDisplayText(sep) Returns a string that contains the code,
description, and price separated by the
sep string.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 34
The Product class (cont.)
Constructor Description
() Creates a Product object with
default values.
(code, description, price) Creates a Product object using
the specified values.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 35
The ProductDB class
Method Description
GetProducts() A static method that returns a List<> of
Product objects from the Products file.
SaveProducts(list) A static method that writes the products
in the specified List<> of Product objects
to the Products file.

Note
 You don’t need to know how the ProductDB class works. You
just need to know about its methods so you can use them in your
code.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 36
The Validator class
Property Description
Title A static string that contains the text
that’s displayed in the title bar of a
dialog box that’s displayed for an
error message.
Returns a Boolean value
Static method that indicates whether…
IsPresent(textBox) Data was entered into the specified
text box.
IsInt32(textBox) An integer was entered into the
specified text box.
IsDecimal(textBox) A decimal was entered into the
specified text box.
IsWithinRange(textBox, min, max) The value entered into the text box
is within the specified range.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 37
The code for the Product Maintenance form
public partial class frmProductMain : Form
{
public frmProductMain()
{
InitializeComponent();
}

private List<Product> products = null;

private void frmProductMain_Load(object sender, EventArgs e)


{
products = ProductDB.GetProducts();
FillProductListBox();
}

private void FillProductListBox()


{
lstProducts.Items.Clear();
foreach (Product p in products)
{
lstProducts.Items.Add(p.GetDisplayText("\t"));
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 38
The code for the Product Maintenance form (cont.)

private void btnAdd_Click(object sender, EventArgs e)


{
frmNewProduct newProductForm = new frmNewProduct();
Product product = newProductForm.GetNewProduct();
if (product != null)
{
products.Add(product);
ProductDB.SaveProducts(products);
FillProductListBox();
}
}

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 + "?";

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 39
The code for the Product Maintenance form (cont.)

DialogResult button =
MessageBox.Show(message, "Confirm Delete",
MessageBoxButtons.YesNo);
if (button == DialogResult.Yes)
{
products.Remove(product);
ProductDB.SaveProducts(products);
FillProductListBox();
}
}
}

private void btnExit_Click(object sender, EventArgs e)


{
this.Close();
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 40
The code for the New Product form
public partial class frmNewProduct : Form
{
public frmNewProduct()
{
InitializeComponent();
}

private Product product = null;

public Product GetNewProduct()


{
this.ShowDialog();
return product;
}

private void btnSave_Click(object sender, EventArgs e)


{
if (IsValidData())
{
product = new Product(txtCode.Text, txtDescription.Text,
Convert.ToDecimal(txtPrice.Text));
this.Close();
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 41
The code for the New Product form (cont.)
private bool IsValidData()
{
return Validator.IsPresent(txtCode) &&
Validator.IsPresent(txtDescription) &&
Validator.IsPresent(txtPrice) &&
Validator.IsDecimal(txtPrice);
}

private void btnCancel_Click(object sender, EventArgs e)


{
this.Close();
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 42
The code for the Validator class
public static class Validator
{
private static string title = "Entry Error";

public static string Title


{
get
{
return title;
}
set
{
title = value;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 43
The code for the Validator class (cont.)
public static bool IsPresent(TextBox textBox)
{
if (textBox.Text == "")
{
MessageBox.Show(textBox.Tag + " is a required field.",
Title);
textBox.Focus();
return false;
}
return true;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 44
The code for the Validator class (cont.)
public static bool IsDecimal(TextBox textBox)
{
decimal number = 0m;
if (Decimal.TryParse(textBox.Text, out number))
{
return true;
}
else
{
MessageBox.Show(textBox.Tag +
" must be a decimal value.", Title);
textBox.Focus();
return false;
}
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 45
The syntax for coding
an auto-implemented property
public type PropertyName { get; [set;] } [= value]

An auto-implemented property
with both get and set accessors
public string Code { get; set; }

An auto-implemented property
with a get accessor and an initial value
public string Code { get; } = "CS15";

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 46
A statement that sets the value
of an auto-implemented property
product.Code = txtProductCode.Text;

A statement that gets the value


of an auto-implemented property
string code = product.Code;

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 47
A read-only property
public decimal DiscountAmount
{
get
{
return subtotal * discountPercent;
}
}

The same property using an expression body


public decimal DiscountAmount => subtotal * discountPercent;

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 48
A method that returns the value
of an expression
public string GetDisplayText(string sep)
{
return code + sep + price.ToString("c") + sep + description;
}

The same method using an expression body


public string GetDisplayText(string sep) =>
code + sep + price.ToString("c") + sep + description;

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 49
A method that executes a single statement
public void DisplayProduct()
{
MessageBox.Show("Code: " + code + "\n" +
"Price: " + price.ToString("c") + "\n"
"Description: " + description, "Product");
}

The same method using an expression body


public void DisplayProduct() =>
MessageBox.Show("Code: " + code + "\n" +
"Price: " + price.ToString("c") + "\n" +
"Description: " + description, "Product");

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 50
Using live code analysis to generate a class

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 51
Using live code analysis
to generate a method stub

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 52
The Product class in the Solution Explorer
with references to the Price property displayed*

*Community Edition doesn’t have the CodeLens feature that lets you
display references.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 53
A class diagram that shows two of the classes

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 54
A Peek Definition window
with the code for the GetDisplayText method

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 55
The syntax for creating a structure
public struct StructureName
{
structure members...
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 56
A Product structure
public struct Product
{
private string code;
private string description;
private decimal price;

public Product(string code, string description, decimal price)


{
this.code = code;
this.description = description;
this.price = price;
}
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 57
A Product structure (cont.)
.
.
public string GetDisplayText(string sep)
{
return Code + sep + Price.ToString("c") + sep + Description;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 58
Code that declares a variable as a structure type
and assigns values to it
// Create an instance of the Product structure
Product p;

// Assign values to each instance variable


p.Code = "CS15";
p.Description = "Murach's C# 2015";
p.Price = 56.50m;

// Call a method
string msg = p.GetDisplayText("\n");

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 59
Code that uses the default constructor
to initialize the instance variables
Product p = new Product();

Code that uses the constructor that accepts


parameters to initialize the instance variables
Product p = new Product("CS15", "Murach's C# 2015",
56.50m);

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 60
Extra 12-1 Create and use an Inventory Item class

Add a class for an inventory item to the Inventory


Maintenance application and then add the code that uses
this class.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 61
Project 3-1 Create a basic calculator

Create a form that lets the user perform the operations of


a basic calculator, and create a class that performs those
operations.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 62
Project 3-2 Assign tickets with time slots

Develop an application that assigns tickets that include a


time slot when a guest can return to visit an attraction
without waiting in line.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 63
Project 3-2 Assign tickets with time slots (cont.)

Develop a form that lets the user specify the number of


minutes for each time slot, the number of guests allowed
during each time slot, the time the attraction opens and
closes, and the number for the first ticket.

Murach's © 2016, Mike Murach & Associates, Inc.


C12, Slide 64
Chapter 13

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

Murach's © 2016, Mike Murach & Associates, Inc.


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

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 66
The code for a simple ProductList class
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);
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 67
The code for a simple ProductList class (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);

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 68
The ProductList class
Constructor Description
() Creates a new product list.
Indexer Description
[index] Provides access to the product at the specified
position.
[code] Provides access to the product with the
specified code.
Property Description
Count An integer that indicates how many Product
objects are in the list.
Method Description
Add(product) Adds the specified Product object to the list.

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 69
The ProductList class (cont.)
Method Description
Add(code, description, price) Creates a Product object
with the specified code,
description, and price values,
and then adds the Product
object to the list.
Remove(product) Removes the specified
Product object from the list.
Fill() Fills the list with product
data from a file.
Save() Saves the products to a file.

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 70
The ProductList class (cont.)
Operator Description
+ Adds a Product object to the list.
- Removes a Product object from the list.
Delegate Description
ChangeHandler Can be used to register the method that’s used
to handle the Changed event.
Event Description
Changed Raised whenever a Product object is added to,
updated in, or removed from the list.

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 71
An indexer that uses an integer as an index
private List<Product> products;

public Product this[int i]


{
get
{
return products[i];
}
set
{
products[i] = value;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 72
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;
}
}

A read-only indexer with an expression body


public Product this[int i] => products[i];

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 73
Code that uses these indexers
ProductList products = new ProductList();
products.Add("CS15", "Murach's C# 2015", 56.50m);
Product p1 = products[0];
Product p2 = products["CS15"];
products[i] = new Product(code, description, price);

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 74
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];
}
...
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 75
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 (p.Code == code)
return p;
}
return null;
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 76
Three argument exceptions
Exception 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.

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 77
An if statement that validates data
before setting a property value
Product p = null;
if (txtCode.Text.Length <= 4)
p = products[txtCode.Text];

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 78
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);

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 79
Code in a form that uses the delegate
public partial class frmProducts : Form
{
// create the delegate 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"));
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 80
Code in a form that uses the delegate (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);
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 81
The syntax for declaring an event
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
}
...
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 82
Code in a form that wires the event handler and
handles the event
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"));
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 83
How to create a delegate
using an anonymous method
ProductList.ChangeHandler myDelegate =
delegate (ProductList products)
{
Console.WriteLine("The products list has changed!");
for (int i = 0; i < products.Count; i++) { ... }
};
myDelegate(products);

How to create a delegate


using a lambda expression
ProductList.ChangeHandler myDelegate = products =>
{
Console.WriteLine("The products list has changed!");
for (int i = 0; i < products.Count; i++) { ... }
};
myDelegate(products);

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 84
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 =>
{
Console.WriteLine("The products list has changed!");
for (int i = 0; i < products.Count; i++) { ... }
};

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 85
The syntax for overloading unary operators
public static returnType operator
unary-operator(type operand)

The syntax for overloading binary operators


public static returnType operator
binary-operator(type-1 operand-1, type-2 operand-2)

Common operators you can overload


Unary operators
+ - ! ++ -- true false

Binary operators
+ - * / % & | == != > < >= <=

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 86
The Equals method of the Object class
Method 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.

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 87
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;
}
.
.
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 88
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;

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 89
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);

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 90
Code that overloads the == operator
for a Product class
public static bool operator == (Product p1, Product p2)
{
if (Object.Equals(p1, null))
if (Object.Equals(p2, null))
return true;
else
return false;
else
return p1.Equals(p2);
}

public static bool operator != (Product p1, Product p2)


{
return !(p1 == p2);
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 91
Code that overloads the == operator
for a Product class (cont.)
public override bool Equals(Object obj)
{
if (obj == null)
return false;
Product p = (Product)obj;
if (this.Code == p.Code &&
this.Description == p.Description &&
this.Price == p.Price)
return true;
else
return false;
}

public override int GetHashCode()


{
string hashString = this.Code + this.Description
+ this.Price;
return hashString.GetHashCode();
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 92
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.

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 93
The code for the 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;

Murach's © 2016, Mike Murach & Associates, Inc.


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

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 95
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);

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 96
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);
Changed(this);
}

public void Remove(Product product)


{
products.Remove(product);
Changed(this);
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 97
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);
return pl;
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 98
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"));
}
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 99
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);

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 100
The code for the Product Maintenance form (cont.)

if (button == DialogResult.Yes)
{
products -= product;
}
}
}

private void btnExit_Click(object sender, EventArgs e)


{
this.Close();
}

private void HandleChange(ProductList products)


{
products.Save();
FillProductListBox();
}

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 101
Lab 05 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.

Murach's © 2016, Mike Murach & Associates, Inc.


C13, Slide 102

You might also like