SlideShare a Scribd company logo
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 1
Chapter 15
How to work with
interfaces and generics
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 2
Objectives
Applied
1. Use .NET interfaces as you develop the classes for an application.
2. Develop and use your own interfaces.
Knowledge
1. Distinguish between an interface and an abstract class.
2. Describe the use of the .NET ICloneable, IComparable<>, and
IEnumerable<> interfaces.
3. In general terms, describe the use of generic interfaces.
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 3
The IDisplayable interface
interface IDisplayable
{
string GetDisplayText(string sep);
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 4
A Product class that implements the IDisplayable
interface
public class Product : IDisplayable
{
public string Code { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public Product(string Code, string Description,
decimal Price)
{
this.Code = Code;
this.Description = Description;
this.Price = Price;
}
public string GetDisplayText(string sep)
{
return this.Code + sep + this.Description
+ sep + this.Price.ToString("c");
}
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 5
Code that uses the IDisplayable interface
IDisplayable product = new Product("CS10",
"Murach's C# 2010", 54.5m);
Console.WriteLine(product.GetDisplayText("n"));
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 6
A comparison of interfaces and abstract classes
• Both interfaces and abstract classes provide signatures for
properties and methods that a class must implement.
• All of the members of an interface are abstract. In contrast, an
abstract class can implement some or all of its members.
• A class can inherit only one class (including abstract classes), but
a class can implement more than one interface.
• Interfaces can’t declare static members, but abstract classes can.
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 7
Commonly used .NET interfaces
Interface Members
ICloneable object Clone()
IComparable int CompareTo(object)
IConvertible TypeCode GetTypeCode()
decimal ToDecimal()
int ToInt32()
(etc.)
IDisposeable void Dispose()
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 8
Commonly used .NET interfaces for collections
Interface Members
IEnumerable IEnumerator GetEnumerator()
IEnumerator object Current
bool MoveNext()
void Reset()
ICollection int Count
bool IsSynchronized
object SyncRoot
void CopyTo(array, int)
IList [int] void Remove(object)
int Add(object) void RemoveAt(int)
void Clear()
IDictionary [int] int Add(object)
ICollection Keys void Remove(object)
ICollection Values void Clear()
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 9
The syntax for creating an interface
public interface InterfaceName
{
type MethodName(parameters); // Declares a method
type PropertyName // Declares a property
{
[get;] // Declares a get accessor
[set;] // Declares a set accessor
}
...
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 10
An interface that defines one method
public interface IDisplayable
{
string GetDisplayText(string sep);
}
An interface that defines two methods and a
property
public interface IPersistable
{
object Read(string id);
bool Save(object o);
bool HasChanges
{
get;
set;
}
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 11
The syntax for creating an interface that inherits
other interfaces
public interface InterfaceName : InterfaceName1
[, InterfaceName2...]
{
interface members...
}
An interface that inherits two interfaces
public interface IDataAccessObject : IDisplayable,
IPersistable
{
// add additional members here
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 12
The syntax for implementing an interface
public class ClassName : [BaseClassName,] InterfaceName1
[, InterfaceName2]...
A Product class that implements ICloneable
public class Product : ICloneable
A Product class that implements two interfaces
public class Product : ICloneable, IDisplayable
A class that inherits a class and implements two
interfaces
public class Book : Product, ICloneable, IDisplayable
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 13
The prompt that’s displayed when you enter an
interface name
The code that’s generated when you implement
the interface
#region ICloneable Members
public object Clone()
{
throw new Exception(
"The method or operation is not implemented.");
}
#endregion
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 14
The code that’s generated when you explicitly
implement the interface
#region ICloneable Members
object ICloneable.Clone()
{
throw new Exception(
"The method or operation is not implemented.");
}
#endregion
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 15
The code for the cloneable Product class
public class Product : IDisplayable, ICloneable
{
public string Code { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public Product(string Code, string Description,
decimal Price)
{
this.Code = Code;
this.Description = Description;
this.Price = Price;
}
#region IDisplayable Members
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 16
The code for the cloneable Product class (cont.)
public string GetDisplayText(string sep)
{
return this.Code + sep + this.Description
+ sep + this.Price.ToString("c");
}
#endregion
#region ICloneable Members
public object Clone()
{
Product p = new Product();
p.Code = this.Code;
p.Description = this.Description;
p.Price = this.Price;
return p;
}
#endregion
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 17
Code that creates and clones a Product object
Product p1 = new Product("JAV5",
"Murach's Beginning Java 2, SDK 5", 52.50m);
Product p2 = (Product)p1.Clone();
p2.Code = "JSE6";
p2.Description = "Murach's Java SE 6";
Console.WriteLine(p1.GetDisplayText("n") + "n");
Console.WriteLine(p2.GetDisplayText("n") + "n");
The output that’s displayed by this code
JAV5
Murach's Beginning Java 2, SDK 5
$52.50
JSE6
Murach's Java SE 6;
$52.50
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 18
A CreateList method that uses an interface as a
parameter
public static List<object> CreateList(ICloneable obj,
int count)
{
List<object> objects = new List<object>();
for (int i = 0; i < count; i++)
{
object o = obj.Clone();
objects.Add(o);
}
return objects;
}
A WriteToConsole method that uses an interface
as a parameter
public static void WriteToConsole(IDisplayable d)
{
Console.WriteLine(d.GetDisplayText("n") + "n");
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 19
Code that uses the methods
Product product = new Product("CS10",
"Murach's C# 2010", 54.50m);
List<object> products = CreateList(product, 3);
foreach (Product p in products)
{
WriteToConsole(p);
}
The output displayed by this code
CS10
Murach's C# 2010
$54.50
CS10
Murach's C# 2010
$54.50
CS10
Murach's C# 2010
$54.50
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 20
A CustomList<> class that uses generics
public class CustomList<T>
{
private List<T> list = new List<T>();
// an Add method
public void Add(T item)
{
list.Add(item);
}
// a read-only indexer
public T this[int i]
{
get
{
return list[i];
}
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 21
A CustomList<> class that uses generics (cont.)
// a read-only property
public int Count
{
get
{
return list.Count;
}
}
// the ToString method
public override string ToString()
{
string listString = "";
for (int i = 0; i < list.Count; i++)
{
listString += list[i].ToString() + "n";
}
return listString;
}
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 22
Code that uses the CustomList<> class
// Test 1
Console.WriteLine("List 1 - ints");
CustomList<int> list1 = new CustomList<int>();
int i1 = 11;
int i2 = 7;
list1.Add(i1);
list1.Add(i2);
Console.WriteLine(list1.ToString());
// Test 2
Console.WriteLine("List 2 - Products");
CustomList<Product> list2 = new CustomList<Product>();
Product p1 = new Product("VB10",
"Murach's Visual Basic 2010", 54.50m);
Product p2 = new Product("CS10", "Murach's C# 2010",
54.50m);
list2.Add(p1);
list2.Add(p2);
Console.Write(list2.ToString());
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 23
Output that results from the Test 1 & Test 2 code
List 1 - ints
11
7
List 2 - Products
VB10 Murach's Visual Basic 2010 $54.50
CS10 Murach's C# 2010 $54.50
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 24
A commonly used generic .NET interface
Interface Members
IComparable<> int CompareTo(T)
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 25
Commonly used .NET interfaces for generic
collections
Interface Members
IEnumerable<> IEnumerator<T>
GetEnumerator()
ICollection<> int Count
bool IsReadOnly
T SyncRoot
Add(T)
void Clear()
bool Contains(T)
void CopyTo(array, int)
bool Remove(T)
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 26
Commonly used .NET interfaces for generic
collections (cont.)
Interface Members
IList<> [int]
int IndexOf(T)
void Insert(int, T)
void RemoveAt(int)
IDictionary<> [int]
ICollection<K> Keys
ICollection<V> Values
void Add(K, V)
bool ContainsKey(K)
bool Remove(K)
bool TryGetValue(K, V)
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 27
A class that implements the IComparable<>
interface
public class Product : IComparable<Product>
{
public string Code { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
// other members
#region IComparable<Product> Members
public int CompareTo(Product other)
{
return this.Code.CompareTo(other.Code);
}
#endregion
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 28
Code that uses the Product class
Product p1 = new Product("VB10",
"Murach's Visual Basic 2010", 54.50m);
Product p2 = new Product("CS10", "Murach's C# 2010",
54.50m);
int compareValue = p1.CompareTo(p2);
if (compareValue > 0)
Console.WriteLine("p1 is greater than p2");
else if (compareValue < 0)
Console.WriteLine("p1 is less than p2");
else if (compareValue == 0)
Console.WriteLine("p1 is equal to p2");
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 29
Values that can be returned by the CompareTo
method
Value Meaning
-1 The current element is less than the compare element.
0 The current element is equal to the compare element.
1 The current element is greater than the compare element.
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 30
A class that uses a constraint
public class CustomList<T> where T: class, IComparable<T>
{
private List<T> list = new List<T>();
// an Add method that keeps the list sorted
public void Add(T item)
{
if (list.Count == 0)
{
list.Add(item);
}
else
{
for (int i = 0; i < list.Count; i++)
{
T currentItem = list[i];
T nextItem = null;
if (i < list.Count - 1)
{
nextItem = list[i + 1];
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 31
A class that uses a constraint (cont.)
int currentCompare =
currentItem.CompareTo(item);
if (nextItem == null)
{
if (currentCompare >= 0)
{
list.Insert(i, item);
// insert before current item
break;
}
...
...
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 32
Keywords that can be used to define constraints
Keyword Description
class The type argument must be a class.
struct The type argument must be a structure.
new() The type argument must have a default constructor.
You can’t use this keyword when the type argument
must be a structure.
A class that uses constraints
public class StructList<T> where T: struct
Another class that uses constraints
public class ProductList<T> where T: Product,
IComparable<T>, new()
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 33
A class that implements the IEnumerable<>
interface
public class CustomList<T> : IEnumerable<T>
{
private List<T> list = new List<T>();
// other members
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
foreach (T item in list)
{
yield return item;
}
}
#endregion
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 34
A class that implements the IEnumerable<>
interface (cont.)
#region IEnumerable Members
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
throw new Exception(
"The method or operation is not implemented.");
}
#endregion
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 35
Code that uses the CustomList class
Product p1 = new Product("VB10",
"Murach's Visual Basic 2010", 54.50m);
Product p2 = new Product("CS10", "Murach's C# 2010",
54.50m);
CustomList<Product> list = new CustomList<Product>();
list.Add(p1);
list.Add(p2);
foreach (Product p in list)
{
Console.WriteLine(p.ToString());
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 36
An interface named IGenericPersistable<> that
uses generics
interface IGenericPersistable<T>
{
T Read(string id);
bool Save(T obj);
bool HasChanges
{
get;
set;
}
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 37
A class that implements the
IGenericPersistable<> interface
class Customer : IGenericPersistable<Customer>
{
// other members
#region IGenericPersistable<Customer> Members
public Customer Read(string id)
{
throw new Exception(
"The method or operation is not implemented.");
}
public bool Save(Customer obj)
{
throw new Exception(
"The method or operation is not implemented.");
}
Murach’s C#
2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 38
A class that implements the
IGenericPersistable<> interface (cont.)
public bool HasChanges
{
get
{
throw new Exception(
"The property is not implemented.");
}
set
{
throw new Exception(
"The property is not implemented.");
}
}
#endregion
}

More Related Content

PPTX
Microservices Architecture
PDF
Iterative process planning.pdf
PDF
Design patterns difference between interview questions
PPT
Project duration and staffing
PPT
1 2. project management
PPTX
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
PPTX
The sqa unit and other actors in the sqa system
PPTX
typescript.pptx
Microservices Architecture
Iterative process planning.pdf
Design patterns difference between interview questions
Project duration and staffing
1 2. project management
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
The sqa unit and other actors in the sqa system
typescript.pptx

Viewers also liked (18)

PPT
C# Tutorial MSM_Murach chapter-13-slides
PPT
C# Tutorial MSM_Murach chapter-07-slides
PPT
C# Tutorial MSM_Murach chapter-14-slides
PPT
C# Tutorial MSM_Murach chapter-08-slides
PPT
C# Tutorial MSM_Murach chapter-09-slides
PPT
C# Tutorial MSM_Murach chapter-12-slides
PDF
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
PPT
Basic c#
PPTX
Fluent interface in c#
PPT
1.Philosophy of .NET
PPT
C# Tutorial MSM_Murach chapter-18-slides
PPT
C# Tutorial MSM_Murach chapter-21-slides
PPT
C# Tutorial MSM_Murach chapter-22-slides
PPT
C# Tutorial MSM_Murach chapter-25-slides
PPT
C# Tutorial MSM_Murach chapter-24-slides
PPT
C# Tutorial MSM_Murach chapter-19-slides
PPT
C# Tutorial MSM_Murach chapter-16-slides
PPT
C# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-13-slides
C# Tutorial MSM_Murach chapter-07-slides
C# Tutorial MSM_Murach chapter-14-slides
C# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-12-slides
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)
Basic c#
Fluent interface in c#
1.Philosophy of .NET
C# Tutorial MSM_Murach chapter-18-slides
C# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-25-slides
C# Tutorial MSM_Murach chapter-24-slides
C# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-20-slides
Ad

Similar to C# Tutorial MSM_Murach chapter-15-slides (20)

PDF
Joel Landis Net Portfolio
PPT
C# Tutorial MSM_Murach chapter-03-slides
DOCX
C# Unit 2 notes
PPTX
4. Types, Objects and NameSPACES in. Net.pptx
PPT
C# Tutorial MSM_Murach chapter-04-slides
PPTX
Interfaces c#
PDF
Btech chapter notes batcha ros zir skznzjsbaajz z
PDF
.NET Portfolio
PPTX
Object Oriented Programming with Object Orinted Concepts
PPT
C# Tutorial MSM_Murach chapter-23-slides
PDF
Introduction to c#
PDF
Introduction To Csharp
DOC
Framework Project Portfolio
PDF
Object-oriented programming (OOP) with Complete understanding modules
PPTX
CSharp presentation and software developement
PDF
Conventional and Reasonable
PPTX
Polymorphism and interface in vb.net
PDF
Dotnet unit 4
DOC
10266 developing data access solutions with microsoft visual studio 2010
PPT
CSharp_03_ClassesStructs_and_introduction
Joel Landis Net Portfolio
C# Tutorial MSM_Murach chapter-03-slides
C# Unit 2 notes
4. Types, Objects and NameSPACES in. Net.pptx
C# Tutorial MSM_Murach chapter-04-slides
Interfaces c#
Btech chapter notes batcha ros zir skznzjsbaajz z
.NET Portfolio
Object Oriented Programming with Object Orinted Concepts
C# Tutorial MSM_Murach chapter-23-slides
Introduction to c#
Introduction To Csharp
Framework Project Portfolio
Object-oriented programming (OOP) with Complete understanding modules
CSharp presentation and software developement
Conventional and Reasonable
Polymorphism and interface in vb.net
Dotnet unit 4
10266 developing data access solutions with microsoft visual studio 2010
CSharp_03_ClassesStructs_and_introduction
Ad

More from Sami Mut (13)

PPT
C# Tutorial MSM_Murach chapter-17-slides
PPT
C# Tutorial MSM_Murach chapter-11-slides
PPT
C# Tutorial MSM_Murach chapter-10-slides
PPT
C# Tutorial MSM_Murach chapter-06-slides
PPT
C# Tutorial MSM_Murach chapter-05-slides
PPT
C# Tutorial MSM_Murach chapter-02-slides
PPT
C# Tutorial MSM_Murach chapter-01-slides
DOCX
MSM_Time
PPT
chapter 5 Java at rupp cambodia
PPT
chapter 2 Java at rupp cambodia
PPT
chapter 3 Java at rupp cambodia
PPT
chapter 2 Java at rupp cambodia
PPT
chapter 1 Java at rupp cambodia
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-11-slides
C# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-01-slides
MSM_Time
chapter 5 Java at rupp cambodia
chapter 2 Java at rupp cambodia
chapter 3 Java at rupp cambodia
chapter 2 Java at rupp cambodia
chapter 1 Java at rupp cambodia

Recently uploaded (20)

PDF
Review of recent advances in non-invasive hemoglobin estimation
PPT
Teaching material agriculture food technology
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation theory and applications.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
A Presentation on Artificial Intelligence
PDF
cuic standard and advanced reporting.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Machine learning based COVID-19 study performance prediction
Review of recent advances in non-invasive hemoglobin estimation
Teaching material agriculture food technology
Chapter 3 Spatial Domain Image Processing.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Network Security Unit 5.pdf for BCA BBA.
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation theory and applications.pdf
Assigned Numbers - 2025 - Bluetooth® Document
MYSQL Presentation for SQL database connectivity
sap open course for s4hana steps from ECC to s4
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Spectroscopy.pptx food analysis technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
A comparative analysis of optical character recognition models for extracting...
A Presentation on Artificial Intelligence
cuic standard and advanced reporting.pdf
20250228 LYD VKU AI Blended-Learning.pptx
The AUB Centre for AI in Media Proposal.docx
Advanced methodologies resolving dimensionality complications for autism neur...
Machine learning based COVID-19 study performance prediction

C# Tutorial MSM_Murach chapter-15-slides

  • 1. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 1 Chapter 15 How to work with interfaces and generics
  • 2. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 2 Objectives Applied 1. Use .NET interfaces as you develop the classes for an application. 2. Develop and use your own interfaces. Knowledge 1. Distinguish between an interface and an abstract class. 2. Describe the use of the .NET ICloneable, IComparable<>, and IEnumerable<> interfaces. 3. In general terms, describe the use of generic interfaces.
  • 3. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 3 The IDisplayable interface interface IDisplayable { string GetDisplayText(string sep); }
  • 4. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 4 A Product class that implements the IDisplayable interface public class Product : IDisplayable { public string Code { get; set; } public string Description { get; set; } public decimal Price { get; set; } public Product(string Code, string Description, decimal Price) { this.Code = Code; this.Description = Description; this.Price = Price; } public string GetDisplayText(string sep) { return this.Code + sep + this.Description + sep + this.Price.ToString("c"); } }
  • 5. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 5 Code that uses the IDisplayable interface IDisplayable product = new Product("CS10", "Murach's C# 2010", 54.5m); Console.WriteLine(product.GetDisplayText("n"));
  • 6. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 6 A comparison of interfaces and abstract classes • Both interfaces and abstract classes provide signatures for properties and methods that a class must implement. • All of the members of an interface are abstract. In contrast, an abstract class can implement some or all of its members. • A class can inherit only one class (including abstract classes), but a class can implement more than one interface. • Interfaces can’t declare static members, but abstract classes can.
  • 7. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 7 Commonly used .NET interfaces Interface Members ICloneable object Clone() IComparable int CompareTo(object) IConvertible TypeCode GetTypeCode() decimal ToDecimal() int ToInt32() (etc.) IDisposeable void Dispose()
  • 8. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 8 Commonly used .NET interfaces for collections Interface Members IEnumerable IEnumerator GetEnumerator() IEnumerator object Current bool MoveNext() void Reset() ICollection int Count bool IsSynchronized object SyncRoot void CopyTo(array, int) IList [int] void Remove(object) int Add(object) void RemoveAt(int) void Clear() IDictionary [int] int Add(object) ICollection Keys void Remove(object) ICollection Values void Clear()
  • 9. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 9 The syntax for creating an interface public interface InterfaceName { type MethodName(parameters); // Declares a method type PropertyName // Declares a property { [get;] // Declares a get accessor [set;] // Declares a set accessor } ... }
  • 10. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 10 An interface that defines one method public interface IDisplayable { string GetDisplayText(string sep); } An interface that defines two methods and a property public interface IPersistable { object Read(string id); bool Save(object o); bool HasChanges { get; set; } }
  • 11. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 11 The syntax for creating an interface that inherits other interfaces public interface InterfaceName : InterfaceName1 [, InterfaceName2...] { interface members... } An interface that inherits two interfaces public interface IDataAccessObject : IDisplayable, IPersistable { // add additional members here }
  • 12. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 12 The syntax for implementing an interface public class ClassName : [BaseClassName,] InterfaceName1 [, InterfaceName2]... A Product class that implements ICloneable public class Product : ICloneable A Product class that implements two interfaces public class Product : ICloneable, IDisplayable A class that inherits a class and implements two interfaces public class Book : Product, ICloneable, IDisplayable
  • 13. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 13 The prompt that’s displayed when you enter an interface name The code that’s generated when you implement the interface #region ICloneable Members public object Clone() { throw new Exception( "The method or operation is not implemented."); } #endregion
  • 14. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 14 The code that’s generated when you explicitly implement the interface #region ICloneable Members object ICloneable.Clone() { throw new Exception( "The method or operation is not implemented."); } #endregion
  • 15. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 15 The code for the cloneable Product class public class Product : IDisplayable, ICloneable { public string Code { get; set; } public string Description { get; set; } public decimal Price { get; set; } public Product(string Code, string Description, decimal Price) { this.Code = Code; this.Description = Description; this.Price = Price; } #region IDisplayable Members
  • 16. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 16 The code for the cloneable Product class (cont.) public string GetDisplayText(string sep) { return this.Code + sep + this.Description + sep + this.Price.ToString("c"); } #endregion #region ICloneable Members public object Clone() { Product p = new Product(); p.Code = this.Code; p.Description = this.Description; p.Price = this.Price; return p; } #endregion }
  • 17. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 17 Code that creates and clones a Product object Product p1 = new Product("JAV5", "Murach's Beginning Java 2, SDK 5", 52.50m); Product p2 = (Product)p1.Clone(); p2.Code = "JSE6"; p2.Description = "Murach's Java SE 6"; Console.WriteLine(p1.GetDisplayText("n") + "n"); Console.WriteLine(p2.GetDisplayText("n") + "n"); The output that’s displayed by this code JAV5 Murach's Beginning Java 2, SDK 5 $52.50 JSE6 Murach's Java SE 6; $52.50
  • 18. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 18 A CreateList method that uses an interface as a parameter public static List<object> CreateList(ICloneable obj, int count) { List<object> objects = new List<object>(); for (int i = 0; i < count; i++) { object o = obj.Clone(); objects.Add(o); } return objects; } A WriteToConsole method that uses an interface as a parameter public static void WriteToConsole(IDisplayable d) { Console.WriteLine(d.GetDisplayText("n") + "n"); }
  • 19. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 19 Code that uses the methods Product product = new Product("CS10", "Murach's C# 2010", 54.50m); List<object> products = CreateList(product, 3); foreach (Product p in products) { WriteToConsole(p); } The output displayed by this code CS10 Murach's C# 2010 $54.50 CS10 Murach's C# 2010 $54.50 CS10 Murach's C# 2010 $54.50
  • 20. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 20 A CustomList<> class that uses generics public class CustomList<T> { private List<T> list = new List<T>(); // an Add method public void Add(T item) { list.Add(item); } // a read-only indexer public T this[int i] { get { return list[i]; } }
  • 21. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 21 A CustomList<> class that uses generics (cont.) // a read-only property public int Count { get { return list.Count; } } // the ToString method public override string ToString() { string listString = ""; for (int i = 0; i < list.Count; i++) { listString += list[i].ToString() + "n"; } return listString; } }
  • 22. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 22 Code that uses the CustomList<> class // Test 1 Console.WriteLine("List 1 - ints"); CustomList<int> list1 = new CustomList<int>(); int i1 = 11; int i2 = 7; list1.Add(i1); list1.Add(i2); Console.WriteLine(list1.ToString()); // Test 2 Console.WriteLine("List 2 - Products"); CustomList<Product> list2 = new CustomList<Product>(); Product p1 = new Product("VB10", "Murach's Visual Basic 2010", 54.50m); Product p2 = new Product("CS10", "Murach's C# 2010", 54.50m); list2.Add(p1); list2.Add(p2); Console.Write(list2.ToString());
  • 23. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 23 Output that results from the Test 1 & Test 2 code List 1 - ints 11 7 List 2 - Products VB10 Murach's Visual Basic 2010 $54.50 CS10 Murach's C# 2010 $54.50
  • 24. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 24 A commonly used generic .NET interface Interface Members IComparable<> int CompareTo(T)
  • 25. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 25 Commonly used .NET interfaces for generic collections Interface Members IEnumerable<> IEnumerator<T> GetEnumerator() ICollection<> int Count bool IsReadOnly T SyncRoot Add(T) void Clear() bool Contains(T) void CopyTo(array, int) bool Remove(T)
  • 26. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 26 Commonly used .NET interfaces for generic collections (cont.) Interface Members IList<> [int] int IndexOf(T) void Insert(int, T) void RemoveAt(int) IDictionary<> [int] ICollection<K> Keys ICollection<V> Values void Add(K, V) bool ContainsKey(K) bool Remove(K) bool TryGetValue(K, V)
  • 27. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 27 A class that implements the IComparable<> interface public class Product : IComparable<Product> { public string Code { get; set; } public string Description { get; set; } public decimal Price { get; set; } // other members #region IComparable<Product> Members public int CompareTo(Product other) { return this.Code.CompareTo(other.Code); } #endregion }
  • 28. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 28 Code that uses the Product class Product p1 = new Product("VB10", "Murach's Visual Basic 2010", 54.50m); Product p2 = new Product("CS10", "Murach's C# 2010", 54.50m); int compareValue = p1.CompareTo(p2); if (compareValue > 0) Console.WriteLine("p1 is greater than p2"); else if (compareValue < 0) Console.WriteLine("p1 is less than p2"); else if (compareValue == 0) Console.WriteLine("p1 is equal to p2");
  • 29. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 29 Values that can be returned by the CompareTo method Value Meaning -1 The current element is less than the compare element. 0 The current element is equal to the compare element. 1 The current element is greater than the compare element.
  • 30. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 30 A class that uses a constraint public class CustomList<T> where T: class, IComparable<T> { private List<T> list = new List<T>(); // an Add method that keeps the list sorted public void Add(T item) { if (list.Count == 0) { list.Add(item); } else { for (int i = 0; i < list.Count; i++) { T currentItem = list[i]; T nextItem = null; if (i < list.Count - 1) { nextItem = list[i + 1]; }
  • 31. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 31 A class that uses a constraint (cont.) int currentCompare = currentItem.CompareTo(item); if (nextItem == null) { if (currentCompare >= 0) { list.Insert(i, item); // insert before current item break; } ... ...
  • 32. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 32 Keywords that can be used to define constraints Keyword Description class The type argument must be a class. struct The type argument must be a structure. new() The type argument must have a default constructor. You can’t use this keyword when the type argument must be a structure. A class that uses constraints public class StructList<T> where T: struct Another class that uses constraints public class ProductList<T> where T: Product, IComparable<T>, new()
  • 33. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 33 A class that implements the IEnumerable<> interface public class CustomList<T> : IEnumerable<T> { private List<T> list = new List<T>(); // other members #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { foreach (T item in list) { yield return item; } } #endregion
  • 34. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 34 A class that implements the IEnumerable<> interface (cont.) #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new Exception( "The method or operation is not implemented."); } #endregion }
  • 35. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 35 Code that uses the CustomList class Product p1 = new Product("VB10", "Murach's Visual Basic 2010", 54.50m); Product p2 = new Product("CS10", "Murach's C# 2010", 54.50m); CustomList<Product> list = new CustomList<Product>(); list.Add(p1); list.Add(p2); foreach (Product p in list) { Console.WriteLine(p.ToString()); }
  • 36. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 36 An interface named IGenericPersistable<> that uses generics interface IGenericPersistable<T> { T Read(string id); bool Save(T obj); bool HasChanges { get; set; } }
  • 37. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 37 A class that implements the IGenericPersistable<> interface class Customer : IGenericPersistable<Customer> { // other members #region IGenericPersistable<Customer> Members public Customer Read(string id) { throw new Exception( "The method or operation is not implemented."); } public bool Save(Customer obj) { throw new Exception( "The method or operation is not implemented."); }
  • 38. Murach’s C# 2010, C15 © 2010, Mike Murach & Associates, Inc.Slide 38 A class that implements the IGenericPersistable<> interface (cont.) public bool HasChanges { get { throw new Exception( "The property is not implemented."); } set { throw new Exception( "The property is not implemented."); } } #endregion }