I'm in the immediate window in Visual Studio. There's a variable p
. How can I deduce the type of the variable p
?
I tried p.GetType()
but that returns the type of object p
. In my case, this is a very specific type (eg. sometimes ChessPlayer
, sometimes TennisPlayer
). I'd like to know the type of the variable, ie. the type that determines what methods are available on the variable p
.
Edit: I think this is a reasonable thing to want to do. I am trying to inspect the variable p
but I don't know it is! Normally in Visual Studio I just hover the mouse on the variable and it tells me its type, or I type .
and the autocomplete lists its methods. However none of that works in the immediate window, all I have is this variable p
I don't know what it is or what I can do with it :(
c# provides many ways for this :)
For the exact copy of specific type you need to do this
if (p.GetType() == typeof(YourDesiredType))
If you want to know whether p is an instance of yourdesiredtype then
if (p is YourDesiredType)
or you can try this
YourDesiredType ydp = p as YourDesiredType;
As in this case (as i'm not sure that it is possible in your scenario)when OP wants to know the compile type Then I would only recommend to use a generic list for this
Because by keeping Type safe list , everyone can easily keep track for its type
Surprised this was so difficult, in the end I wrote this method, which seems to give the right answer.
public static class Extensions
{
public static Type GetVariableType<T>(this T instance)
{
return typeof(T);
}
}
Example usage:
void Main()
{
IList x = new List<int>{};
x.GetVariableType().Dump();
}
Prints System.Collections.IList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With