C# has duck typing

C# 2.0 has duck typing.

No really, I swear!

Krzysztof Cwalina has a post on Duck Notation which I find very interesting.

Normally in .NET and thus C# to iterate you would use IEnumerable. You can call GetEnumerator yourself and call MoveNext from the implemented IEnumerator interface on the returned IEnumerable. Or 99 times out of 100 you use foreach.

The foreach operator in C# doesn’t use IEnumerable. I was so curious I just HAD to try it.

List<string> list = new List<string>(); 
foreach (string item in new C()) { 
	list.Add(item); 
} 
public class C { 
	public E GetEnumerator() { 
		return new E(); 
	} 
} 
public class E { 
	int x = 0; 
	string[] values = { "hello", "world", "foo", "bar", "baz" }; 
	public bool MoveNext() { 
		return x < values.Length; 
} 
	public string Current { 
		get { return values[x++]; } 
	} 
} 

Neither IEnumerable nor IEnumerator are used here, in fact IEnumerator would require the Reset method to be implemented. It is not present here. (Even though Reset is only there for COM interop and often just throws NotSupportedException, it is at least there.)

Also interesting is that there IS some type checking here. If you make the Current property of type object you get no type checking and in this case you would get a runtime InvalidCastException if you tried to add the result to a List<SomethingNotString>.

Is this useful? I don’t know. Maybe in edge cases. I still like IEnumerable<T> and with the extension methods coming in .NET 3.5 I REALLY want IEnumerable<T> to be a lot of places that it might not be if the above were used extensively.

The biggest problem with C# 3.0 is that it isn’t out yet. The second biggest problem with C# 3.0 is that the language features enable use of awesome things in .NET 3.5 and it isn’t out yet either. The third biggest problem with C# 3.0 is that all those awesome .NET 3.5 things need to be distributed so rollout of Framework 3.5 to servers and desktops might discourage your average organization from using an awesome piece of technology.