I don't know if there is a built in way to do it but the following generic method would do the trick:
void Main()
{
object x = "this is actually a string";
Console.WriteLine(GetCompileTimeType(x));
}
public Type GetCompileTimeType<T>(T inputObject)
{
return typeof(T);
}
This method will return the type System.Object
since generic types are all worked out at compile time.
Just to add I'm assuming that you are aware that typeof(object)
would give you the compile time type of object
if you needed it to just be hardcoded at compile time. typeof
will not allow you to pass in a variable to get its type though.
This method can also be implemented as an extension method in order to be used similarly to the object.GetType
method:
public static class MiscExtensions
{
public static Type GetCompileTimeType<T>(this T dummy)
{ return typeof(T); }
}
void Main()
{
object x = "this is actually a string";
Console.WriteLine(x.GetType()); //System.String
Console.WriteLine(x.GetCompileTimeType()); //System.Object
}
var
is syntactic-sugar for type-inference to avoid having to specify the type in a local variable declaration, it makes no semantic difference nor reveal anything at runtime. – Myxomax.GetType()
returnsSystem.Object
and notSystem.String
, since the variable is of typeobject
, then the answer by Chris is correct. – Neodymium