Search code examples
c#regexidisposableienumeratordispose

Cleaning up with IDisposable issues


I am trying to call these functions to get rid of stuff I don't need, but my code seems to be defeating me in what I am begining to perceive to be a vain struggle. I have tried multiple ways to solve these last two errors, but the IEnumerator is giving me wild cards. errors are on the lines : if (enumerator2 is IDisposable) and if (enumerator is IDisposable)

        try
        {
            enumerator = matchs.GetEnumerator();
            while (enumerator.MoveNext())
            {
                IEnumerator enumerator2;
                Match current = (Match) enumerator.Current;
                num = 0;
                try
                {
                    enumerator2 = current.Groups.GetEnumerator();
                    while (enumerator2.MoveNext())
                    {
                        Group group = (Group) enumerator2.Current;
                        strArray[num, num3] = group.Value;
                        num++;
                    }
                }
                finally
                {
                    if (enumerator2 is IDisposable)
                    {
                        (enumerator2 as IDisposable).Dispose();
                    }
                }
                if (num2 < num3)
                {
                    num2 = num3;
                }
                num3++;
            }
        }
        finally
        {
            if (enumerator is IDisposable)
            {
                (enumerator as IDisposable).Dispose();
            }
        }
        strArray[num, 0] = Conversions.ToString((int) (num2 + 1));
        return strArray;
    }

Edit- Specific error messages: Use of unassigned local variable 'enumerator2'
Use of unassigned local variable 'enumerator'


Solution

  • You should use a foreach loop as pointed out by others.

    But, the reason you are getting that error is because when enumerator2 is used in the finally block, the compiler cannot know that it gets set to some value (because it may not be in some exceptional situations). You can fix your code as-is, by doing:

    IEnumerator enumerator2 = null;
    Match current = ...