Posts

Showing posts from October, 2010

Roles in C# Implementation

After seeing what roles in C# might look like, let's see the necessary transformations that would enable them. This is one possibility that a C# compiler could use to implement roles without having to make changes to the underlying CLR. Roles A role is transformed into a set of types: an interface (which the compositions will implement), a static class with the role code, and a class that encapsulates the role state. The interface for the role is the most important type and it will carry the role name. Because all the generated types are related, they'll be packaged together as nested types inside the role interface. Nesting types inside an interface is not supported in C#, but is supported by the underlying CIL. So we'll be looking at some invalid C# along the way; just think of it as "decompiled" CIL. Let's see these transformations for a simple role: role RPrintableWithCount { int count = 0; public void Print() { Console.WriteLine("

Roles in C#

Traits (pdf) are described as composable units of behavior, and are a natural evolutionary path for languages like C# or Java. Microsoft must be seriously looking at them, since it's sponsored some research about Traits in C# (pdf) . I'll describe what I think is an extension to the traits idea that would make a great feature in C# (and in Java, VB.NET, ...): roles. Roles are already a reality in Perl 5, with the Moose::Roles module. They even have their own syntax in Perl 6 . They help create better organized and reusable code, are an effective and safer alternative to multiple inheritance, and have explicit semantics (which means no surprises) as opposed to mixins. What I'll describe here is based on the theoretical traits (as described in the traits paper), on Perl roles and on Scala traits , all adapted to C#. A role is, like a class, a type that holds behavior and state. It can be composed into a type (either a class, a struct or another role) to make its memb