I collect the type of a calling class using:
var type = new StackFrame(1).GetMethod().DeclaringType;
If the class is of type SomeType<T>
I want to know the runtime type of T
, but I can't get it to work.
I have this method that gets the type name which will be called recursively when a type contains generic types. When i run this method with a type I collect using GetType()
it works and returns for instance SomeType<Int32>
as string. But when I run the method using GetCurrentMethod().DeclaringType
it will return SomeType<T>
as string.
My method for creating a type name string:
private string GetTypeString(Type type)
{
var typeString = type.Name;
if (type.IsGenericType)
{
var genericTypeNames = type.GetGenericArguments().Select(ar => GetTypeString(ar));
// When a type is generic, it will be formatted as Type`x (the next line of code will strip the `x)
var strippedTypeName = typeString.Substring(0, typeString.IndexOf("`"));
var genericTypeString = string.Join(",", genericTypeNames);
typeString = $"{strippedTypeName}<{genericTypeString}>";
}
return typeString;
}
Example (to show what the result of both methods is):
public class SomeType<T>
{
}
public static class Main
{
public void Run()
{
SomeType<bool> myClass = new SomeType();
// This works, but I cannot use it in my application, because I collect the class type using StackFrame
var type = myClass.GetType();
var output = GetTypeString(type); // This returns "SomeType<bool>"
// This doesn't work:
type = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
output = GetTypeString(type); // This returns "SomeType<T>"
}
The first example shows that using GetType()
gives me the result I want. However I cannot use this, because where I want to create the type string I cannot call GetType() on the class. I get the type using StackFrame
. The second examples shows the result when I get the type via `GetMethod().DeclaringType'. The outcome is different and not what I am searching for. Does anyone have any tips or suggestions?
The reality:
public class SomeType<T>
{
private class Log = new Log();
}
public class Log
{
private string typeString;
public Log()
{
var type = new StackFrame(1).GetMethod().DeclaringType; // This collects type of the calling class, in this case 'SomeType<T>'
typeString = GetTypeString(type); // This constructs the type string, but is not able to determine the type of T
}
}