.NET Iterator for API Transfer

I have a class with an API that allows me to query objects until it throws an IndexOutOfBoundsException .

I want to wrap it in an iterator to write cleaner code. However, I need to catch an exception to stop the repetition:

 static IEnumerable<object> Iterator( ExAPI api ) { try { for( int i = 0; true; ++i ) { yield return api[i]; // will throw eventually } } catch( IndexOutOfBoundsException ) { // expected: end of iteration. } } 

But...

When used with an expression, return cannot appear in a catch or in a try block that has one or more catch. For more information, see Expression Exception Handling (C # Link). Statements (C # Link). (from msdn )

How can I put this api?

+7
c # exception yield-return
Oct 28 '10 at 13:04 on
source share
5 answers

You just need to move the yield return outside the try block, for example:

 static IEnumerable<object> Iterator( ExAPI api ) { for( int i = 0; true; ++i ) { object current; try { current = api[i]; } catch(IndexOutOfBoundsException) { yield break; } yield return current; } } 
+14
Oct 28 2018-10-28
source share

You can wrap a simple operation of obtaining an object in a separate function. You can catch the exception:

 bool TryGetObject( ExAPI api, int idx, out object obj ) { try { obj = api[idx]; return true; } catch( IndexOutOfBoundsException ) { return false; } } 

Then call this function and complete if necessary:

 static IEnumerable<object> Iterator( ExAPI api ) { bool abort = false; for( int i = 0; !abort; ++i ) { object obj; if( TryGetObject( api, i, out obj ) ) { yield return obj; } else { abort = true; } } } 
+4
Oct 28 2018-10-28
source share

Just change the order of the code:

 static IEnumerable<object> Iterator( ExAPI api ) { bool exceptionThrown = false; object obj = null; for( int i = 0; true; ++i ) { try { obj = api[i]; } catch( IndexOutOfBoundsException ) { exceptionThrown = true; yield break; } if (!exceptionThrown) { yield return obj; } } } 
0
Oct 28 '10 at 13:10
source share

If you can’t check the boundaries of an object at all, you can do something like this

 static IEnumerable<object> Iterator( ExAPI api ) { List<object> output = new List<object>(); try { for( int i = 0; true; ++i ) output.Add(api[i]); } catch( IndexOutOfBoundsException ) { // expected: end of iteration. } return output; } 

although now when I look here, the answer is above, I believe. One SLaks came out.

0
Oct 28 2018-10-28
source share
  static IEnumerable<object> Iterator(ExAPI api) { int i = 0; while (true) { Object a; try { a = api[i++]; } catch (IndexOutOfBoundsException) { yield break; } yield return a; } } 
0
Oct 28 '10 at 13:18
source share



All Articles