0

I have the following method which uses yield return.

public static IEnumerable<T> GetSourceData<T>(int parentId) where T :class
{
 Type documentType = typeof(T);
 var shouldThrow = documentType.Namespace.StartsWith("Data.Company.Documents") == false;

 if (shouldThrow)
 {
    throw new InvalidOperationException(string.Format("message here"));
 }

 /// Some more code goes on here
}

I have stepped through this code in the debugger and shouldThrow is false, but the control still continues on to throw the exception. Is this some silly thing with methods that are generic AND they use yield return?

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
fahadash
  • 3,133
  • 1
  • 30
  • 59
  • 3
    It's probably more readable to write `! condition` instead of `condition == false` – dcastro May 13 '15 at 15:26
  • 2
    just to double check, is `shouldThrow` is `false` or `documentType.Namespace.StartsWith("Data.Company.Documents")` is returning `false` ? – Habib May 13 '15 at 15:28
  • Where is the `yield`? Are you enumerating the collection by watching it in the debugger? I would add data to the throw to make sure you are throwing on the same one you are debugging. – Ron Beyer May 13 '15 at 15:29
  • Yup, replace `var shouldThrow = ...` with `var shouldThrow = false` and try again. If the exception is still being thrown, try to come up with a [Minimal Complete and Verifiable Example](http://stackoverflow.com/help/mcve) – dcastro May 13 '15 at 15:29
  • @dcastro It depends. Is `not condition` or `condition is false` more understandable to say? – IS4 May 13 '15 at 15:30
  • @IllidanS4 I would say `not startswith` is easier to understand than `startswith == false`, but you're right, it's highly subjective. – dcastro May 13 '15 at 15:31
  • @RonBeyer Question has it "shouldThrow" is false – fahadash May 13 '15 at 15:31
  • Yes, I understand, but using the debugger while iterating an enumerable has strange results because the debugger will walk the entire iterator chain in a watch, which can look like strange results. Adding a little message to the exception can verify you are throwing on the one you are looking at in the code view. – Ron Beyer May 13 '15 at 15:33
  • Are you sure you're stepping through the same code? This could be caused by building the binaries wrong. Add something to the code that ensures you're actually running the code you think you're running. Something like `Debug.WriteLine("Yup, new code");`. – Luaan May 13 '15 at 15:33
  • Whoever posted an answer earlier and deleted it, please repost it. Because you were right, I can't remember what your handle was. Turns out it was Debugger trolling me, the actual exception isn't thrown – fahadash May 13 '15 at 15:35

0 Answers0