Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get compile time type of a variable?

I'm looking for how to get compile time type of a variable for debugging purposes.

The testing environment can be reproduced as simply as:

object x = "this is actually a string";
Console.WriteLine(x.GetType());

Which will output System.String. How could I get the compile time type System.Object here?

I took a look over at System.Reflection, but got lost in the amount of possibilities it provides.

like image 917
tomsseisums Avatar asked Jul 23 '14 09:07

tomsseisums


1 Answers

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
}
like image 50
Chris Avatar answered Sep 21 '22 17:09

Chris