In C#, I started seeing all these magic methods popping up, without being backed up by an interface. Why was this chosen?
Let me explain.
Previously in C#, if an object implemented the IEnumerable
interface, it would automatically be iterable by a foreach
loop. That makes sense to me, since it's backed up by an interface, and if I were to have my own Iterator
function inside the class being iterated through, I could do that without worrying that it would magically mean something else.
Now, apparently, (not sure when), these interfaces are no longer required. It just needs to have the right naming conversions.
Another example is making any object awaitable by having a method named exactly GetAwaiter
which has a few specific properties.
Why not make an interface like they did with IEnumerable
or INotifyPropertyChanged
to back this "magic" up statically?
More details on what I mean here:
http://blog.nem.ec/2014/01/01/magic-methods-c-sharp/
What are the pros and cons of magic methods, and is there anywhere online where I can find anything on why these decisions were made?
async
/await
, then that will only work with code that was written after .NET 4.5 became wide-spread enough to be a viable target … which is basically now. But a purely syntactic translation into method calls allows me to addawait
functionality to existing types after the fact.foreach
loop back in the beginning. There never has been a requirement for the object to implementIEnumerable
forforeach
to work. It's just been convention to do so.