Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Framework: Get Type from TypeInfo

The new reflection API introduces the TypeInfo class:
https://docs.microsoft.com/en-us/dotnet/api/system.reflection.typeinfo

I can get a TypeInfo instance of a Type (say, a Car) by writing

TypeInfo typeInfo = typeof(Car).GetTypeInfo();

Now, what if I just have a TypeInfo instance? How do I get the Type it's referring to? Can I just write

Type type = typeInfo.GetType();

Or will this return a type that is equal to typeof(TypeInfo)?

like image 825
Michael Hilus Avatar asked Apr 20 '17 15:04

Michael Hilus


People also ask

How do you get type object from assemblies that are already loaded?

Use Type. GetType to get the Type objects from an assembly that is already loaded.

How do I get TypeInfo?

To get a TypeInfo object from a Type object, use the IntrospectionExtensions. GetTypeInfo(Type) extension method. A TypeInfo object represents the type definition itself, whereas a Type object represents a reference to the type definition. Getting a TypeInfo object forces the assembly that contains that type to load.

What is the return type of GetType in C#?

C# String GetType() The C# GetType() method is used to get type of current object. It returns the instance of Type class which is used for reflection.


1 Answers

If you call typeInfo.GetType(), you will indeed get the execution-time type of the object that typeInfo refers to - so some concrete type derived from TypeInfo.

You want TypeInfo.AsType():

Returns the current type as a Type object.

So your code would be:

Type type = typeInfo.AsType();

Or, as noted in comments, something I'd never noticed: TypeInfo derives from Type! So just use:

Type type = typeInfo;
like image 192
Jon Skeet Avatar answered Oct 31 '22 02:10

Jon Skeet