Indexers don't have to operate on actual arrays : Indexer : Class Interface C# Source Code


Custom Search

C# Source Code » Class Interface » Indexer »

 

Indexers don't have to operate on actual arrays









    

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Indexers don't have to operate on actual arrays. 
 
using System; 
 
class PwrOfTwo {  
 
  /* Access a logical array that contains 
     the powers of 2 from 0 to 15. */ 
  public int this[int index] { 
    // Compute and return power of 2. 
    get { 
      if((index >= 0) && (index < 16)) return pwr(index); 
      else return -1; 
    } 
 
    // there is no set accessor 
  } 
 
  int pwr(int p) { 
    int result = 1; 
 
    for(int i=0; i<p; i++) 
      result *= 2; 
     
    return result; 
  } 
}  
  
public class UsePwrOfTwo {  
  public static void Main() {  
    PwrOfTwo pwr = new PwrOfTwo(); 
 
    Console.Write("First 8 powers of 2: "); 
    for(int i=0; i < 8; i++) 
      Console.Write(pwr[i] + " "); 
    Console.WriteLine(); 
 
    Console.Write("Here are some errors: "); 
    Console.Write(pwr[-1] + " " + pwr[17]); 
 
    Console.WriteLine(); 
  } 
}


           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Class Interface
» Indexer