Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are IEnumerable<T>, Task<T> and IDisposable hard coded in the C# compiler?

Tags:

c#

roslyn

I asked that question myself many times. I tried to find some blog post about that and even dug into the Roslyn source code, but have not found any complete answer on that.

Basically, with some modern C# language features the compiler will take some syntactic sugar and transforms it into more low-level C# code. Some example of those are:

  • using() generates a try-finally to definitely dispose an IDisposable
  • Functions returning an IEnumerable<T> with yield return will turn that function into an iterator implemented as a state machine
  • Functions marked with async have to return Task<T> (or similar) and will turn into a state machine too, which can be re-entered from the programs event-loop under the hood

So, these are all nice features, but the compiler is always enforcing the specific types IEnumerable<T>, Task<T> and IDisposable. Are these types somehow baked into the compiler? And isn't it true that the compiler is somehow bound to the standard library then, even though mscorlib is just plain C# code providing common functionality?

I cannot imagine that since programming languages are so abstract and general. As I have seen there is the possibility for await-ing anything as long as the type has an GetAwaiter extension method. That sounds more abstract to me.

Edit

Also, if anyone can point me to the source code which specifies the required predefined types in the compiler, let me know!

like image 754
Bruno Zell Avatar asked Nov 07 '22 04:11

Bruno Zell


1 Answers

Sort-of.

The compiler has lists of "special" (used in the type-system / binder) and "well-known" (referenced by generated code) types and members, which are hard-coded by name in Roslyn source. However, all that it cares about are the names & methods / signatures of these types / members; you can still write your own mscorlib (and people have done this) as long as it has them.

See

  • http://sourceroslyn.io/#Microsoft.CodeAnalysis/SpecialType.cs
  • http://sourceroslyn.io/#Microsoft.CodeAnalysis/SpecialMember.cs
  • http://sourceroslyn.io/#Microsoft.CodeAnalysis/WellKnownTypes.cs
  • http://sourceroslyn.io/#Microsoft.CodeAnalysis/Symbols/WellKnownMemberNames.cs
like image 133
SLaks Avatar answered Nov 11 '22 15:11

SLaks