Cardinal Fang
Cardinal Fang

Reputation: 283

Generic method - Type cannot be used as Type Parameter

Given the following Generic Method:

    /// <summary>
    /// Performs a MoveNext on the IEnumerator 'Enoomerator'. 
    /// If it hits the end of the enumerable list, it resets to the beginning.
    /// </summary>
    /// <returns>If False, MoveNext has failed even after resetting,
    /// which means there are no entries in the list.</returns>
    private static bool CyclicalSafeMoveNext<T>(T Enoomerator) 
                                           where T : IEnumerator<T> 
    {
        if (Enoomerator.MoveNext()) //  successfully moved to the next element
        {
            return true;
        }
        else
        {
            // Either reached last element (so reset to beginning) or
            // trying to enumerate in a list with no entries 
            LogLine("CyclicalSafeMoveNext: failed a MoveNext, resetting.");
            Enoomerator.Reset();

            if (!Enoomerator.MoveNext())
            {
                // Still at end. Zero entries in the list?
                LogLine("CyclicalSafeMoveNext: failed a MoveNext after 
                Reset(), which means there were no entries in the list.");
                return false;
            }
            else
            {
                // Resetting was successful
                return true;
            }
        }
    }

When I compile this code

IEnumerator<FileInfo> FileInfoEnumerator files;                               
while (CyclicalSafeMoveNext(files))
{
    return files.Current.FullName;
}

I get the error:

Error 7 The type 'System.Collections.Generic.IEnumerator<System.IO.FileInfo>' cannot 
be used as type parameter 'T' in the generic type or method
'CyclicalSafeMoveNext<T>(T)'. There is no implicit reference conversion from
'System.Collections.Generic.IEnumerator<System.IO.FileInfo>' to 'System.Collections.Generic.IEnumerator<System.Collections.Generic.IEnumerator<System.IO.FileInfo>>'.

Why am I getting this error and how do I correct my code?

Upvotes: 1

Views: 122

Answers (2)

D Stanley
D Stanley

Reputation: 152634

One problem is here:

where T : IEnumerator<T> 

You're restricting the generic class to a class that is its own enumerator.

Since FileInfo is not an IEnumerator<FileInfo> and IEnumerator<FileInfo> is not an IEnumerator<IEnumerator<FileInfo>> it fails the generic constraint.

You could add a second generic type:

private static bool CyclicalSafeMoveNext<T, U>(T Enoomerator) 
                                       where T : IEnumerator<U>

or just make IEnumerator<T> part of the signature:

private static bool CyclicalSafeMoveNext<T>(IEnumerator<T> Enoomerator) 

Upvotes: 5

aqwert
aqwert

Reputation: 10789

try

private static bool CyclicalSafeMoveNext<T>(IEnumerator<T> Enoomerator)

having the where T : IEnumerator<T> is throwing it off.

Upvotes: 2

Related Questions