Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeof().GetTypeInfo().Assembly vs typeof().Assembly

Tags:

c#

I've seen examples of both the following code:

typeof(Type).GetTypeInfo().Assembly

And...

typeof(Type).Assembly

I can't see the difference when I've experimented. Even intellisense returns the same documentation. The first seems to be more prevalent. Is there a reason to use one over the other?

like image 226
Andy Cox Avatar asked Jul 09 '20 09:07

Andy Cox


2 Answers

They both do the same thing. IIRC, Type.GetTypeInfo() returns this in (almost?) all cases.

The reason you'll see references to type.GetTypeInfo().Assembly is that the Type.Assembly property wasn't present in .NET Core 1.x, along with a lot of other reflection members. So if you had old .NET Framework code using reflection, you had to sprinkle .GetTypeInfo() all over the place to get it to work with .NET Core 1.x.

The same code continues to work for more modern versions of .NET Core and .NET, but I suspect that many people (such as myself) haven't been bothered to go round and remove all the now-redundant GetTypeInfo() calls.

like image 148
Jon Skeet Avatar answered Oct 23 '22 08:10

Jon Skeet


I was just wondering the exact same thing.

Seems like it's possible that TypeInfo could be more lightweight to use than Type.

Below snippet was grabbed from this article

type vs typeinfo - dailydotnettips

Edit:

As Jon rightly points out this won't be more lightweight for the Assembly property. It seems I was not wondering the exact same thing, instead I was trying to understand the difference between Type and TypeInfo which is explained here.

like image 33
Quinton Smith Avatar answered Oct 23 '22 09:10

Quinton Smith