Distinguish between the type used to refer to the object and the type of its backup storage

using System; interface IAnimal { } class Cat: IAnimal { } class Program { public static void Main(string[] args) { IAnimal cat = new Cat(); // Console.WriteLine(cat.GetType()); // This would only give me the type of // the backing store, ie Cat. Is there a // way I can get to know that the identifier // cat was declared as IAnimal? Console.ReadKey(); } } 

Update: Thanks to Dan Bryant for the reminder.

 using System; using System.Reflection; using System.Collections.Generic; using System.Linq; namespace TypeInfo { class Program { public static void Main(string[] args) { IAnimal myCat = new Cat(); ReflectOnType(); Console.ReadKey(); } public static void ReflectOnType() { Assembly.GetExecutingAssembly(). GetType("TypeInfo.Program"). GetMethod("Main", BindingFlags.Static| BindingFlags.Public). GetMethodBody().LocalVariables. ToList(). ForEach( l => Console.WriteLine(l.LocalType)); } } interface IAnimal { } class Cat : IAnimal { } } 
+6
reflection c #
source share
2 answers

You can use the general type of output:

 using System; internal interface IAnimal { } internal class Cat : IAnimal { } class Program { static void Main() { var cat = new Cat(); Console.WriteLine(cat.GetType()); // Cat Console.WriteLine(GetStaticType(cat)); // Cat IAnimal animal = cat; Console.WriteLine(GetStaticType(animal)); // IAnimal } static Type GetStaticType<T>(T _) { return typeof (T); } } 
+1
source share

Under the assumption above, I am posting this as an answer. See Comments above for further context.


You indicated that you still see the "backup storage" using LocalVariableInfo. For me, this means that the declaration is exclusively in the source and is not encoded in the method at all. The fact that you decide to use the interface as a "declared" type does not matter, because the compiler decided to use a more specific type for the local variable slot. Try running ILdasm on your dll output, and you can see if it is true. If so, your only option is to actually look at the source code, because the information literally does not exist in the compiled version.

0
source share

All Articles