Guest

.NET iterator to wrap throwing API

By: a guest on Feb 23rd, 2012  |  syntax: None  |  size: 1.99 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1. static IEnumerable<object> Iterator( ExAPI api ) {
  2.     try {
  3.        for( int i = 0; true; ++i ) {
  4.           yield return api[i]; // will throw eventually
  5.        }
  6.     }
  7.     catch( IndexOutOfBoundsException ) {
  8.        // expected: end of iteration.
  9.     }
  10. }
  11.        
  12. static IEnumerable<object> Iterator( ExAPI api ) {
  13.    for( int i = 0; true; ++i ) {
  14.         object current;
  15.         try {
  16.             current = api[i];
  17.         } catch(IndexOutOfBoundsException) { yield break; }
  18.  
  19.         yield return current;
  20.     }
  21. }
  22.        
  23. bool TryGetObject( ExAPI api, int idx, out object obj )
  24. {
  25.     try
  26.     {
  27.         obj = api[idx];
  28.         return true;
  29.     }
  30.     catch( IndexOutOfBoundsException )
  31.     {
  32.         return false;
  33.     }        
  34. }
  35.        
  36. static IEnumerable<object> Iterator( ExAPI api )
  37. {
  38.    bool abort = false;
  39.  
  40.     for( int i = 0; !abort; ++i )
  41.     {
  42.         object obj;
  43.         if( TryGetObject( api, i, out obj ) )
  44.         {
  45.             yield return obj;
  46.         }
  47.         else
  48.         {
  49.             abort = true;
  50.         }
  51.     }
  52. }
  53.        
  54. static IEnumerable<object> Iterator( ExAPI api ) {
  55.     bool exceptionThrown = false;
  56.     object obj = null;
  57.     for( int i = 0; true; ++i ) {
  58.         try {
  59.             obj = api[i];
  60.         }
  61.         catch( IndexOutOfBoundsException ) {
  62.             exceptionThrown = true;
  63.             yield break;
  64.         }
  65.  
  66.         if (!exceptionThrown) {
  67.             yield return obj;
  68.         }
  69.     }
  70. }
  71.        
  72. static IEnumerable<object> Iterator( ExAPI api )
  73. {
  74.  List<object> output = new List<object>();
  75.     try
  76.  {
  77.   for( int i = 0; true; ++i )
  78.    output.Add(api[i]);
  79.     }
  80.     catch( IndexOutOfBoundsException )
  81.  {
  82.   // expected: end of iteration.
  83.     }
  84.  return output;
  85. }
  86.        
  87. static IEnumerable<object> Iterator(ExAPI api)
  88.     {
  89.         int i = 0;
  90.         while (true)
  91.         {
  92.             Object a;
  93.             try
  94.             {
  95.                 a = api[i++];
  96.             }
  97.             catch (IndexOutOfBoundsException)
  98.             {
  99.                 yield break;
  100.             }
  101.             yield return a;
  102.         }
  103.     }