This is a mirror of official site: http://jasper-net.blogspot.com/

In bed with Roslyn

| Sunday, October 23, 2011
Microsoft have been talking about their “C# compiler as a service” project, aka Roslyn, for a couple of years now, and yesterday the C# team finally released a preview version. Being a bit of a language geek, I was interested to see if I could use Roslyn not only to perform analysis and refactorings but to extend the C# language itself. The reason for wanting to do this is to replace repetitive and error-prone boilerplate code with terser, more expressive code — quicker to write, easier to read and no chance for human error to muck it up.

The motivating example

If you’ve written much WPF or Silverlight code, you’ve undoubtedly written a bunch of dependency properties. Because C# has no built-in support for DPs, this means you have to write a bunch of code spread across several members, something like this:

public static readonly DependencyProperty WidgetudeProperty =
  DependencyProperty.Register("Widgetude", typeof(int), typeof(Widget),
    new FrameworkPropertyMetadata(OnWidgetudeChanged));
 
public int Widgetude
{
  get { return (int)GetValue(WidgetudeProperty); }
  set { SetValue(WidgetudeProperty, value); }
}
 
private static void OnWidgetudeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  // on-change logic here
}

This is not only boring to write, it is hard to read because the code is cluttered with boilerplate, and it is prone to error. If I had a dollar for everybody who put business logic in the CLR property setter and then wondered why it wasn’t being run when a binding updated… well, I’d have $3.00. And it’s awful to maintain. For example, if I change the property to a double, I have to update the type in three places. If I change the property name, I have to update it in seven!

Read more: MindScape blog
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://www.mindscapehq.com/blog/index.php/2011/10/20/in-bed-with-roslyn/

Posted via email from Jasper-net

0 comments: