Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine type of a variable? (not the type of the object)

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 :(

like image 825
Colonel Panic Avatar asked Nov 21 '12 11:11

Colonel Panic


2 Answers

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

like image 110
Freak Avatar answered Oct 25 '22 10:10

Freak


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

like image 40
Colonel Panic Avatar answered Oct 25 '22 08:10

Colonel Panic