Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly.GetTypes() returns strange type names e.g. "<>c"

Tags:

c#

.net

When using Assembly.GetTypes() I get types that have Type.Name that begin with <>c.....

I tried to google if this is anonymous types or something else. But cannot get a really good answer.

Is there a property on Type that indicate what these types are? I do not like having to do if(type.Name.StartsWith("<>"))

like image 428
Erik Sundström Avatar asked Sep 21 '15 14:09

Erik Sundström


Video Answer


2 Answers

These are compiler generated display classes. You can distinguish them by looking for the CompilerGeneratedAttribute:

var attr = Attribute.GetCustomAttribute(type, typeof(CompilerGeneratedAttribute)); 
like image 113
Yuval Itzchakov Avatar answered Oct 05 '22 23:10

Yuval Itzchakov


They're compiler generated types, which would include anonymous types, but also the implementations of IEnumerable<T>, IEnumerator<T>, IEnumerable and IEnumerator that are produced by yield and the state-machine structures produced by await.

They will have the CompilerGeneratedAttribute.

You describe the names as "strange" and they are deliberately such. They are all names that are valid .NET names, but not valid in common .NET languages, particularly C# and VB.NET. This means you couldn't create such a class with C# coding directly, so there doesn't need to have any logic to check the programmer hasn't created a matching class.

like image 40
Jon Hanna Avatar answered Oct 06 '22 01:10

Jon Hanna