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

I enter the direct window in Visual Studio. There is a variable p . How can I determine the type of the variable p ?

I tried p.GetType() , but returns the type of the object p . In my case, this is a very specific type (for example, sometimes ChessPlayer , sometimes TennisPlayer ). I would like to know the type of a variable, i.e. a type that determines which methods are available for the variable p .


Edit: I think this is a reasonable thing to do. I'm trying to check the variable p , but I don't know what it is! Usually in Visual Studio I just hover over a variable and it tells me its type, or I type . , and autocomplete lists its methods. However, none of this works in the immediate window, all I have is the variable p I don’t know what it is or what I can do with it :(

+7
source share
5 answers

Surprised it was so complicated, in the end I wrote this method, which seems to give the correct answer.

 public static class Extensions { public static Type GetVariableType<T>(this T instance) { return typeof(T); } } 

Usage example:

 void Main() { IList x = new List<int>{}; x.GetVariableType().Dump(); } 

Print System.Collections.IList

+3
source

C # provides many ways to do this:

For an exact copy of a specific type, you need to do this

 if (p.GetType() == typeof(YourDesiredType)) 

If you want to know if 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 (since I'm not sure if this is possible in your scenario), when the OP wants to know the type of compilation, then I would recommend using a generic list for this

Because by keeping a list of safe types, everyone can easily track their type

+5
source

As an alternative to using the direct window, if you want to see only the type of the variable, you can simply add a variable watch and check the type in the viewport.

+1
source
 System.Object.GetType() 

This will return you the type of the variable, because this class is at the top of the hierarchy from which each class is called.

you can also check the typeof function to get the exact type of this instance.

0
source

I think you may need this

 if (p is ChessPlayer) { ChessPlayer cp = (ChessPlayer)p; //Use ChessPlayer methods } 
0
source

All Articles