Why cant we use IteratorStateMachineAttribute in C#?

I did a Go To Definition (F12) on a class I was trying to derive from and I noticed that one of the methods was marked with AsyncStateMachineAttribute. Which in turn inherits StateMachineAttribute. I was curious and decide to read up on this attribute and all its derivates on MSDN. That led me to this and I came across this statement:

You can't use IteratorStateMachineAttribute to test whether a method is an iterator method in C#.

Because that statement is made to stand out, there must be serious implications to it but there is no further explanation as to why that is so. Does anyone have insights in this regard?

Jon Skeet
people
quotationmark

I'm 99% sure it's historical. Basically, C# introduced iterator blocks in C# 2 - a long time before this attribute was introduced.

The equivalent async attribute was introduced at the same time as async methods in C#, so that was fine... but even though the C# compiler now applies IteratorStateMachineAttribute to iterator blocks:

  • It doesn't apply to libraries created with older versions of the compiler, so you wouldn't be able to rely on it there.
  • It can't apply to libraries targeting versions of .NET prior to 4.5. (I'm not sure what the VB compiler does here, to be honest. It may omit the attribute, or it may require you to be targeting a recent version of .NET in order to use iterator methods.)

I would say that the presence of an IteratorStateMachineAttribute on a method is a good indicator that it is an iterator method (although there's nothing to stop a mischievous developer applying it to other methods), but it's not a sufficient test due to older versions of the C# compiler.

people

See more on this question at Stackoverflow