/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Add an indexer in an interface.
using System;
public interface ISeries {
// an interface property
int next {
get; // return the next number in series
set; // set next number
}
// an interface indexer
int this[int index] {
get; // return the specified number in series
}
}
// Implement ISeries.
class ByTwos : ISeries {
int val;
public ByTwos() {
val = 0;
}
// get or set value using a property
public int next {
get {
val += 2;
return val;
}
set {
val = value;
}
}
// get a value using an index
public int this[int index] {
get {
val = 0;
for(int i=0; i val += 2;
return val;
}
}
}
// Demonstrate an interface indexer.
public class SeriesDemo4 {
public static void Main() {
ByTwos ob = new ByTwos();
// access series through a property
for(int i=0; i < 5; i++)
Console.WriteLine("Next value is " + ob.next);
Console.WriteLine("\nStarting at 21");
ob.next = 21;
for(int i=0; i < 5; i++)
Console.WriteLine("Next value is " +
ob.next);
Console.WriteLine("\nResetting to 0");
ob.next = 0;
// access series through an indexer
for(int i=0; i < 5; i++)
Console.WriteLine("Next value is " + ob[i]);
}
}