Implicits instead of Extension Methods?
After the latest round of scala is teh complex, I started thinking a bit more about the similar roles implicit conversions in scala play to extension methods in C#. I can't objectively comment on whether Extension Methods are simpler (they are still a discoverability issue), but I can comment that the idea of implicit conversion to attach new functionality to existing code really intrigued me. It does seem less obvious but also a lot more powerful.
Then i thought, wait, C# has implicit.. Did they just invent extension methods without needing to? I've never used implicit conversion in C# for anything but automatic casting, but maybe I was just not imaginative enough. So here goes nothing:
public class RichInt { public readonly int Value; public static implicit operator RichInt(int i) { return new RichInt(i); } public static implicit operator int(RichInt i) { return i.Value; } private RichInt(int i) { Value = i; } public IEnumerable<int> To(int upper) { for(int i = Value;i<=upper;i++) { yield return i; } } }
Given the above I was hoping I could mimic scala's RichInt
to()
method and write code like this:
foreach(var i in 10.To(20)) { Console.WriteLine(i); }
Alas that won't compile. Implicit conversion only works on assignment, so i had to write
foreach(var i in ((RichInt)10).To(20)) { Console.WriteLine(i); }
So I do have to use an extension method to create To()
in C#.
And, yes, i'm grossly simplifying what scala's implicts can accomplish. Also, I wish I could have block scope using
statements to import extension methods for just a block the way scala's import allows you to handle local scope implicits.
Leave a comment