I have a generic class called Repository. This class has a function that “calls itself” by initializing a new instance of the Repository class with a different generic argument. This “recursion” can go on – so to avoid StackOverflowException, i need to check if there is in the stack, a method called from the Repository class with the same generic argument.
here is my code:
StackTrace stack = new StackTrace();
StackFrame[] frames = stack.GetFrames();
foreach (StackFrame frame in frames)
{
Type callingMethodClassType = frame.GetMethod().DeclaringType;
if (callingMethodClassType.IsGenericType)
{
// BUG HERE in getting generic arguments of the class in stack
Type genericType = callingMethodClassType.GetGenericArguments()[0];
if (genericType.Equals(entityType))
{
wasAlready = true;
break;
}
}
}
the generic type always returns as T and not the correct type like “User” or “Employee” (for example). I can’t compare the names of the types because T does not have a name.
Don’t think that this is possible, because you only get the GenericType, but not the real GenericArguments of the class.
If you look at the return of frame.GetMethod().DeclaringType you’ll notice, that only the GenericType, but not the real GenericArguments are within the debugging result.