Is C# Missing Traits?

Does C# need "traits"? It's always interesting to look at other programming languages for features that aren't available in your main programming language.

First, what the heck is a trait? Traits are a language construct that is unique to Scala. Let's check out how traits work in Scala.

A trait lives somewhere between what we would call an abstract class and an interface in C#.  Traits offer a form of multiple inheritance as you can have many traits on a class and a trait can optionally have behavior as well. You cannot have constructors on a Trait.

Here is an example usage of traits that solves a challenging OOP modeling issue in C#. This example is pulled indirectly from http://joelabrahamsson.com/learning-scala-part-seven-traits/.

abstract class Enemy

trait Flying {
    def flyMessage: String
    def fly() = println(flyMessage)
}

trait Swimming {
    def swim() = println("I'm swimming")
}

trait BreatheFire {
	def breathe() = println("I'm breathing fire")
}

class Orc extends Enemy with Swimming

class Dragon extends Enemy with Swimming with Flying with BreathesFire {
    val flyMessage = "I'm a good flyer"
}

C# would benefit from having traits similar to Scala in some modeling situations.

References