\C#\Interfaces
InterfaceExample.cs
// // Interface example by Josh Santomieri // Santomieri Systems - 08/25/2006 // using System; using System.Collections; ////// Interface for custom lists. /// public interface IMyList { ////// Gets or sets the object at the index i. /// object this[int i] { get; set; } ////// Gets the count of items in the list. /// int Count { get; } ////// Allows you to add an object to the list. /// /// The object to add to the list. void Add(object item); } ////// Represents a list. /// public class MyList : IMyList { private ArrayList _list; ////// Creates a new MyList. /// public MyList() { this._list = new ArrayList(); } ////// Gets or sets the object at index i. (interface declaration) /// public object this[int i] { get { return this._list[i]; } set { this._list[i] = value; } } ////// Gets the count of items in the list. (interface declaration) /// public int Count { get { return this._list.Count; } } ////// Adds an item to the list. /// /// The item to add to the list. public void Add(object item) { this._list.Add(item); } } ////// Represents a list #2. /// public class MyList2 : IMyList { private ArrayList _list; ////// Creates a new MyList. /// public MyList2() { this._list = new ArrayList(); } ////// Gets or sets the object at index i. (interface declaration) /// public object this[int i] { get { return this._list[i]; } set { this._list[i] = value; } } ////// Gets the count of items in the list. (interface declaration) /// public int Count { get { return this._list.Count; } } ////// Adds an item to the list. /// /// The item to add to the list. public void Add(object item) { this._list.Add(item); } } ////// Gets information about a list... /// public class ListInfo { ////// Gets the count of items in a list that uses the IMyList interface /// /// A list of type IMyList. ///The number of items in the list. public static int ItemsInList(IMyList list) { if (list == null) { throw new ArgumentNullException("list"); } return list.Count; } } ////// Represents the main entry point for the program. /// class Program { static void Main(string[] args) { // Create the new list items. MyList list = new MyList(); MyList2 list2 = new MyList2(); // Populate the lists list.Add("test1"); list.Add("test2"); list2.Add("test1"); // Using one function, write out the number of items in the lists... // Output should be: // Items In MyList: 2 // Items In MyList2: 1 Console.WriteLine("Items In MyList: " + ListInfo.ItemsInList(list)); Console.WriteLine("Items In MyList2: " + ListInfo.ItemsInList(list2)); } }