0

Is there a way to get o1 variable type during runtime instead of the instance type it is referencing?

o1.GetVariableType or something like that which returns the compile-time static type of the variable? In o1's case, System.Object rather than System.Double?

Thanks.

{
    double? d1 = 4.4;
    object o1 = d;
    Console.WriteLine(d1.GetType());
    Console.WriteLine(o1.GetType());
}

this prints out

System.Double

System.Double

Edit: Scheme posted the link that actually answered my question.

How to get compile time type of a variable?

Community
  • 1
  • 1
Cee
  • 1
  • 1
  • 6
    Why would you need a method or operation for this? You already know the compile time type (you have to, by definition). – Servy Jun 26 '17 at 21:31
  • as additional note you could use `typeof(object)` or `typeof(double)` to get the type you want – M.kazem Akhgary Jun 26 '17 at 21:34
  • Can you explain what the higher level goal is? What are you trying to achieve by doing this? – Blorgbeard Jun 26 '17 at 21:34
  • Purely for my edification. I want to know if it is possible. Why is this labeled as duplicate when "Type Checking: typeof, GetType, or is? " doesn't answer it? – Cee Jun 26 '17 at 21:34
  • @Scheme That's also the only way to get the `Nullable` type as opposed to just being told it's a `System.Double` – TyCobb Jun 26 '17 at 21:40
  • @Cee My pleasure, i was trying to answer when it got dupped. – axwr Jun 26 '17 at 21:42
  • Note that you are also seeing a weirdness of Nullable here. When a not-null instance of Nullable is cast to an object, it becomes its value, with no Nullable wrapper. GetType() is a non-virtual method of Object, so GetType() on any variable will never return Nullable. See https://stackoverflow.com/questions/6931783/why-gettype-returns-system-int32-instead-of-nullableint32 – David Wright Jun 27 '17 at 00:06

0 Answers0