Add an indexer in an interface : Interface : Class Interface C# Source Code


Custom Search

C# Source Code » Class Interface » Interface »

 

Add an indexer in an interface









    

/*
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<index; 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]); 
  } 
}

           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Class Interface
» Interface