In Scala, I can define structural types as follows:
type Pressable = { def press(): Unit }
This means that I can define a function or method which takes as an argument something that is Pressable, like this:
def foo(i: Pressable) { // etc.
The object which I pass to this function must have defined for it a method called press() that matches the type signature defined in the type – takes no arguments, returns Unit (Scala’s version of void).
I can even use the structural type inline:
def foo(i: { def press(): Unit }) { // etc.
It basically allows the programmer to have all the benefits of duck typing while still having the benefit of compile-time type checking.
Does C# have something similar? I’ve Googled but can’t find anything, but I’m not familiar with C# in any depth. If there aren’t, are there any plans to add this?
No, and no plans that I know of. Only named (rather than structural) subtyping (e.g. interfaces).
(Others may want to see also
http://en.wikipedia.org/wiki/Nominative_type_system
http://en.wikipedia.org/wiki/Structural_type_system
)
(A few people may point out some exotic corner cases, like the
foreachstatement using structural typing forGetEnumerator, but this is the exception rather than the rule.)