Stack overflow calling from generic method to non-generic method.

Stack overflow calling from generic method to non-generic method.

Post by RWQgQ2hhcG » Wed, 29 Mar 2006 10:05:01


In the following code (over-simplified, of course), the generic method calls
itself recursively, quickly resulting in a StackOverflowException:

public T[] GetArray<T>( T value )
{
return GetArray( value );
}

public Array GetArray( object value )
{
return return new ArrayList().ToArray();
}

I assumed the second method would be called because the notation of the call
(lacking the 'generic' brackets) indicated the non-generic method would be
called. Why does this behave this way?
 
 
 

Stack overflow calling from generic method to non-generic method.

Post by Jon Skeet » Wed, 29 Mar 2006 14:24:34


<=?Utf-8?B?RWQgQ2hhcGVs?= <Ed XXXX@XXXXX.COM >>


It's using type inference to call the generic version without
explicitly stating the type involved. T is more specific than object,
hence the compiler is choosing the generic version over the non-generic
version.

If you cast value to object, your call will go to the non-generic
version.

You'd have to look at the specs in detail for the exact steps the
compiler will take.

--
Jon Skeet - < XXXX@XXXXX.COM >
http://www.yqcomputer.com/ ~skeet Blog: http://www.yqcomputer.com/
If replying to the group, please do not mail me too