Thursday, March 04, 2010

A few weeks ago, some of my colleagues and I were discussing the idiosyncrasies of various programming languages (as we often find ourselves doing—we’re kind of geeky that way), when one of us pointed out that the following code is completely valid C++0x syntax:

[](){}();

The “operator soup”1 above defines a C++ lambda expression (denoted by the square brackets) which declares no parameters (the first empty parentheses) or body (the empty curly braces) and is immediately invoked (the final parentheses). Conceptually, this is a nop—an empty lambda that is immediately invoked.

We found ourselves fascinated by this idea of a do-nothing lambda, and went ahead to define the same thing in our respective languages. Our first attempt was C#.

() => { }();

While the code above looks quite pretty, it’s not exactly legal. In C#, lambdas must always have an explicit delegate type, so an ugly type-cast is required in order to compile:

((Action)(() => { }))();

Sigh, so close, yet so dissatisfying!

The stronger notion of type inference in F# allows for much more succinctness.2

(fun () -> ())()

However, my favorite version is written in Visual Basic 10.

Call (Sub() Exit Sub)()

What it lacks in succinctness,3 it makes up for with human-readable clarity.

 

How do you write a do-nothing lambda in your language?

 

1One could also declare the square brackets with either an = or & operator inside to define how variables that are declared in the same scope as the lambda are captured within the lambda function’s closure. It’s amazing how much one can do without typing a single identifier character!

[&](){}();

2Note that the F# example contains a subtle difference from the others in that it returns a value of type Unit. This implies that the entire F# expression could be passed as an argument to another function, but that is not true of the other examples.

3Though it’s the same size as the C# version when unnecessary whitespace characters are removed.

posted on Thursday, March 04, 2010 7:42:19 AM (Pacific Standard Time, UTC-08:00)  #    Comments [14]

kick it on DotNetKicks.com
 Saturday, October 24, 2009

Now that Visual Studio 2010 Beta 2 is finally out the door, I’ve had a bit more time to spend coding on some of my personal projects. Yesterday, I happened upon a cool trick while using the new Generate from Usage feature. It was so helpful to me that I thought others might benefit, so I’m sharing it here.

The Anonymous Type Problem

When you need to project some data from a LINQ expression, anonymous types can be enormously convenient.

C# Query

Because anonymous types are… well… anonymous, they don’t have names that can be expressed in code. This is problematic if you want to expose an anonymous type as the return type of a function. I have run into this problem many times. When refactoring code, it’s easy to get into a situation like the one below.

Broken C# Function

So, how can you get around this problem? Well, there a few possibilities.

  1. You could replace ??? with object and use reflection to get at the properties. (Yuck!)
  2. You could make the function generic and add a parameter to “mumble” the anonymous type.1 (Awkward!)
  3. Assuming C# 4.0, you could replace ??? with dynamic.2 (No compiler errors!)

Because none of these solutions is particularly savory, most of us are forced to create a new named type to replace the anonymous type. Thankfully, there are some fantastic third-party refactoring tools out there that can automate this tedious process, but if you don’t use one of these tools you’re stuck writing the code by hand.

Actually, no, that’s not quite true.

Generate from Usage to The Rescue!

In Visual Studio 2010, the new Generate from Usage feature makes the task of coding up new classes a snap! Just type a new name for the anonymous type in the editor, making the code look like a type constructor followed by an object initializer. Then, press Ctrl+. to expand the smart tag that immediately appears and choose the first suggestion to generate a new class.

Generate Class

Next, expand each smart tag in the object initializer to generate each property.

Generate Property

When you’re finished, you should have a brand new class containing each property, declared as auto-implemented properties. Cool!

Generated Class

For Visual Basic coders, Generate from Usage is even easier. Let’s start with the same LINQ expression in VB. (Notice the lack of the “_” line continuation characters. Hooray for VB10 implicit line continuation!)

VB Query

Just like before, type the name of the new type that you wish to generate and press Ctrl+. to expand the smart tag. After choosing the first suggestion from the smart tag, you’re finished. The VB Generate Class feature will drill into the object initializer and generate all of the necessary properties at the same time that the class is generated.

VB Generate Class

Wrapping Up

Of course, this technique is not without flaws.

  • The resulting type is not immutable like the anonymous type that you’re replacing. To address this, you can easily modify the generated properties to be read-only.
  • The new type does not have the same structural equality semantics that anonymous types have. In practice, I’ve rarely run into an bug caused by anonymous type structural equality, but if this is a concern for you, use one of the excellent third-party tools that account for these differences.

 

1See Wes Dyer's excellent article for an example of this clever trick.
2Check out Bill Wagner's post for details.

posted on Saturday, October 24, 2009 10:01:40 AM (Pacific Standard Time, UTC-08:00)  #    Comments [5]

kick it on DotNetKicks.com
 Tuesday, April 01, 2008

Today is April Fool's Day—the day when many of us celebrate just how gullible we really are. Celebrants enjoy the day by spoofing co-workers and engaging in fun hoaxes and practical jokes.

Over the years, I've personally been the target of many an April Fool's prank. Considering today's date, I'm not sure what to make of the following email that I received this morning. Am I the target of yet another joke?

Congratulations! We are pleased to present you with the 2008 Microsoft® MVP Award! The MVP Award is our way to say thank you for promoting the spirit of community and improving people’s lives and the industry’s success every day. We appreciate your extraordinary efforts in Visual C# technical communities during the past year.

I suppose it's possible that Microsoft has a thoroughly sick sense of humor, and this is just an elaborate hoax. On the other hand, it could be that Microsoft has absolutely no sense of humor and doesn't realize that today isn't the most optimal day to be sending out congratulatory emails.

I feel that I have to give this email two responses:

  1. If this is real, I am completely humbled to be a recipient of the MVP Award this year. Blogging, speaking and educating are activities that I find very rewarding, and it's flattering to be recognized for them.
  2. If this is just an elaborate joke, I'm thoroughly disgusted and saddened by the juvenile attempt at humor. People have feelings, ya' know!

How hard is it to send these emails on March 31st or April 2nd? :-) That would clear up a lot of confusion.

P.S. I know it's real. Thanks Microsoft! I am truly honored. No joke.

posted on Tuesday, April 01, 2008 7:44:09 AM (Pacific Standard Time, UTC-08:00)  #    Comments [10]

kick it on DotNetKicks.com
 Tuesday, February 19, 2008
Greetings fellow F#-philes! Today we're looking at another reason that I am completely infatuated with the F# language—pattern matching.

Pattern matching is a simple idea. Essentially, a pattern match takes an input and a set of rules. Each rule tests the input against a pattern and returns a result if they match.

The following naive implementation of the tired, old Fibonacci function shows simple pattern matching at work.

#light

let rec fib n =
  match n with
  | 0 -> 0
  | 1 -> 1
  | _ -> fib(n - 1) + fib(n - 2)

Pattern matching syntax is simple and clear. It should be readable by any programmer worth their salt. In fact, the above match .. with block is completely equivalent to the following C# switch statement:

static int Fib(int n)
{
  switch (n)
  {
    case 0:
      return 0;
    case 1:
      return 1;
    default:
      return Fib(n - 1) + Fib(n - 2);
  }
}

That's pretty unimpressive. I mean, if pattern matching were identical to standard switch statements, there really would be nothing exciting about them. Fortunately, there are some enormous differences that demote switch statements to a very distant cousin.

The first difference is subtle but profound: pattern matches return values. A pattern match is very much like a function that takes an argument and returns a value. Consider the following rewrite of our F# fib function:

#light

let rec fib n =
  let result = match n with
               | 0 -> 0
               | 1 -> 1
               | _ -> fib(n - 1) + fib(n - 2)
  result

The above example might be a bit contrived, but it illustrates the point. Simulating that with a switch statement is awkward.

static int Fib(int n)
{
  int result;
  switch (n)
  {
    case 0:
      result = 0;
      break;
    case 1:
      result = 1;
      break;
    default:
      result = Fib(n - 1) + Fib(n - 2);
      break;
  }
  return result;
}

Switch statements don't return values, so we can't assign a switch statement to a variable. Instead, we must use mutable state and pepper the cases with break statements. In essence, a pattern match is like a function while a switch statement is like a big GOTO.

In addition, pattern matching supports a wealth of features that truly set it apart from standard imperative switch statements.

Patterns can:

  1. Contain guard rules (e.g. match x but only when x is less than zero).
  2. Bind values to names.
  3. Decompose type structures.

Let's examine each of these in turn.

First, consider our original fib function with an additional pattern containing a guard rule:

#light

let rec fib n =
  match n with
  | _ when n < 0 -> failwith "value cannot be less than 0."
  | 0 -> 0
  | 1 -> 1
  | _ -> fib(n - 1) + fib(n - 2)

Now that's a bit more interesting! In C# or Visual Basic, we would have to introduce an if-statement at the beginning of the function to test for an invalid argument. In F#, the guard is inserted directly as a pattern rule.

Another indispensible feature of F# pattern matching is the ability to bind values to names.

So far, we've used the match .. with syntax to define pattern matches. This time, we'll use an alternative syntax that, although it is not required, easily demonstrates how values can be bound to names within pattern rules.

The alternative syntax can be used in the case where a function is defined with one argument and simply returns the result of a pattern match on that argument. In this syntax, the argument is not specified, and the keyword function is inserted. The match .. with statement needs to reference the argument name, but because the argument is unspecified, it has no name. Consequently, the match .. with statement must be removed, leaving us with a function that is defined entirely in terms of pattern matching rules. Because the argument is unnamed, values must be bound to names within the pattern rules.

A code sample is worth a thousand words.

#light

let rec fib = function
  | x when x < 0 -> failwith "value cannot be less than 0."
  | 0 | 1 as x -> x
  | x -> fib(x - 1) + fib(x - 2)

In the above code, we bind the name x in each pattern to make up for the fact that the argument is unspecified. In addition, the rules for 0 and 1 and have been combined using an "or" (or "union") pattern. Note that there are two different ways to bind a value to a name within a pattern rule. First, a name can simply be explicitly specified, substituted within the pattern. The other way is to use the as keyword. Both ways are demonstrated above.

The last feature of pattern matching that we'll look at is its capability to decompose type structures.

Recently, we saw that F# would automatically convert the result of Dictionary<TKey, TValue>.TryGetValue to a tuple if a variable isn't specified for the out parameter. In a comment to that article, Derek Slager presented a helper function that returns a default value if TryGetValue returns false. This helper function is an excellent practical example of a pattern match that decomposes a tuple value.

#light

open System.Collections.Generic

let getValueOrDefault (dict : #IDictionary<'a,'b>) key defaultValue =
  match dict.TryGetValue key with
  | true, value -> value
  | _ -> defaultValue

In addition to the tuple decomposition, the first rule elegantly binds the second part of the tuple to the name value. Sweet!

Because pattern matching is intrinsic to F# programming, we'll see more of it in upcoming articles. As features supporting pattern matching are introduced in this series, we'll build on the basics presented here.

Next up: the option type. See you then!

posted on Tuesday, February 19, 2008 7:39:00 AM (Pacific Standard Time, UTC-08:00)  #    Comments [5]

kick it on DotNetKicks.com
 Tuesday, January 29, 2008
As promised, today I'm demonstrating a compelling way in which F# uses tuples to make .NET programming more elegant.

A question that comes up early in F# demonstrations is, "Can I use F# to access code written in my favorite .NET language, <BLANK>?" The answer is an emphatic yes. F# is a first-class .NET citizen that compiles to the same IL as any other .NET language. Consider the following code:

> #light
- open System.Collections.Generic
-
- let d = new Dictionary<int, string>()
- d.Add(1, "My")
- d.Add(2, "F#")
- d.Add(3, "Dictionary");;

val d : Dictionary<int,string>

> d;;
val it : Dictionary<int,string> = dict [(1, "My"); (2, "F#"); (3, "Dictionary")]

The above code1 instantiates a new System.Collections.Generic.Dictionary<TKey, TValue> for int and string, and adds three key/value pairs to it. Note that Dictionary is not written in F#. It is part of the .NET base class library, written in C#.

Retrieving values from d is easy. We simply pass the value's key to the dictionary's indexer like so:

> d.[1];;

val it : string = "My"

> d.[3];;

val it : string = "Dictionary"

However, if we pass a key that isn't found in the dictionary, an exception is thrown.2

> d.[4];;

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
   at System.ThrowHelper.ThrowKeyNotFoundException()
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at <StartupCode$FSI_0013>.FSI_0013._main()
stopped due to error

Fortunately, Dictionary provides a function that allows us to query using an invalid key without throwing an exception. This function, TryGetValue, has the following signature (shown in C#):

bool TryGetValue(TKey key, out TValue value)

The purpose of TryGetValue is obvious. If key is found, the function returns true and the value is returned in the output parameter3. If key is not found, the function returns false and value contains some throwaway data. The C# code below demonstrates how this function might be used.

using System;
using System.Collections.Generic;

class Program
{
  static void Main()
  {
    var d = new Dictionary<int, string>();
    d.Add(1, "My");
    d.Add(2, "C#");
    d.Add(3, "Dictionary");

    string v;
    if (d.TryGetValue(4, out v))
      Console.WriteLine(v);
  }
}

So, how can we use this function in F#? Well, there're a few ways.

The first approach is almost exactly the same as the C# version above. First, we declare a variable to pass as the output parameter. Note that this variable must be declared as mutable so TryGetValue can modify it.

> let mutable v = "";;

val mutable v : string

Now, we can call TryGetValue, passing v by reference.

> d.TryGetValue(1, &v);;

  d.TryGetValue(1, &v);;
  -----------------^^^

stdin(19,17): warning: FS0051: The address-of operator may result in non-verifiable code.
Use only when passing byrefs to functions that require them.

val it : bool = true

> v;;

val it : string = "My"

OK. That worked but displayed an ugly warning about non-verifiable code. Yikes! Fortunately, F# provides another way to declare variables which support mutation: reference cells.4

Declaring a variable as a reference cell is trivial:

> let v = ref "";;

val v : string ref

We can pass the reference cell into TryGetValue without receiving that nasty warning.

> d.TryGetValue(2, v);;

val it : bool = true

> !v;;

val it : string = "F#"

That's much better.

At this point, many of you are probably thinking, "Wait a minute! Wasn't this article supposed to be about tuples? What's all this mutable-variable-output-parameter stuff?" Don't worry. There's a method to my madness. Are you ready?

Consider what happens if we call TryGetValue without specifying a variable for the output parameter:

> let res = d.TryGetValue(3);;

val res : bool * string

> res;;

val it : bool * string = (true, "Dictionary")

Did you catch that? When calling a function containing output parameters in F#, you don't have to specify variables for them. The F# compiler will automatically consolidate the function's result and output parameters into a tuple (in this case, a pair). Awesome! If you were paying attention last time, you've probably already realized that we can bind the TryGetValue call to a pattern that extracts the values from the resulting pair.

> let res, v = d.TryGetValue(2);;

val res : bool
val v : string

> res;;

val it : bool = true

> v;;

val it : string = "F#"

Now, we can easily query our dictionary using an invalid key without an exception being thrown. Best of all, we don't have to declare an awkward mutable variable to store the value. What takes two lines of code in C# consumes just one in F#.

> let res, v = d.TryGetValue(4);;

val res : bool
val v : string

> res;;

val it : bool = false

It is the attention to detail that makes it a joy to code with F#. This is just one example of how F# can consume .NET framework classes in ways more elegant than even C#, the lingua franca of the .NET universe!

I haven't decided what the next article will cover yet. Are there any requests? Feel free to email them to dustin AT diditwith.net.

1The #light directive in the first line of the code sample enables the F# lightweight syntax. We'll look closer at this in a future article.
2This might be frustrating to users of the System.Collections.Hashtable class from .NET Framework 1.0. Unlike Dictionary, Hashtable returns null when a key isn't found rather than throwing an exception. The reason for this behavior difference is detailed here.
3Normally, I would consider the use of output parameters to be a code smell. However, TryGetValue is an example of a scenario where an output parameter is justified.
4We'll be looking more deeply into reference cells in a future article.

posted on Tuesday, January 29, 2008 11:30:29 AM (Pacific Standard Time, UTC-08:00)  #    Comments [3]

kick it on DotNetKicks.com
 Tuesday, January 01, 2008
It's a new year! Time to return to my passion: torturing programming languages and making them cry like little children.

This article has bit of everything: Scheme, C# and VB lambda expressions, closures, lambda calculus... the works. By the end, you'll either be enlightened or stark, raving mad.

Happy New Year!

posted on Tuesday, January 01, 2008 1:33:25 PM (Pacific Standard Time, UTC-08:00)  #    Comments [3]

kick it on DotNetKicks.com
 Friday, December 28, 2007

Cookies

Welcome back for more X-mas refactoring fun! There are just four more verses in my carol, but I'll make them count. Refactor! Pro can bless your Visual Studio 2008 installation in many more ways, so I'll have to pick the very best.

"On the ninth day of X-mas my true love (DevExpress) gave to me..."

Expand Lambda Expression

In my sixth verse, I described a feature of Refactor! Pro that enables developers to leverage the dreaded lambda expressions. That refactoring (Compress to Lambda Expression) provides a way to transform an anonymous method into a lambda expression. Today we're looking at lambda expressions from the opposite perspective—transforming a lambda expression into an anonymous method. Expand Lambda Expression is the refactoring that performs this conversion. Given the lambda expression in the code below...

using System;

namespace TwelveDaysOfXmas
{
  class Program
  {
    static void Main()
    {
      var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

      var numberText = Array.ConvertAll<int, string>(numbers, n => n.ToString("x8"));

      foreach (var text in numberText)
        Console.WriteLine(text);
    }
  }
}

Expand Lambda Expression will produce this:

using System;

namespace TwelveDaysOfXmas
{
  class Program
  {
    static void Main()
    {
      var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

      var numberText = Array.ConvertAll<int, string>(numbers, delegate(int n)
                                                              {
                                                                return n.ToString("x8");
                                                              });

      foreach (var text in numberText)
        Console.WriteLine(text);
    }
  }
}

I'm sure that some of you are scratching your heads. "Why in the world would I want to do that? Aren't lambda expressions better?" Well, yes. However, transforming a lambda expression into an anonymous method makes other refactorings available. For example, after expanding our lambda expression, we might want to use Name Anonymous Method to make the anonymous method a member of the current type. That way, we're promoting code reuse. Check out the preview hint for Name Anonymous Method below.

Name Anonymous Method Preview Hint

Once Name Anonymous Method is applied, we can give the new method a good name and we're done!

using System;

namespace TwelveDaysOfXmas
{
  class Program
  {
    private static string GetHexText(int n)
    {
      return n.ToString("x8");
    }
    static void Main()
    {
      var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

      var numberText = Array.ConvertAll<int, string>(numbers, GetHexText);

      foreach (var text in numberText)
        Console.WriteLine(text);
    }
  }
}

View Screencast of Expand Lambda Expression and Name Anonymous Method in Action!

I must say, it gladdens my heart to know that there is a tool available right now that allows me to refactor the latest and greatest language features of Visual Studio 2008. In fact, we've raised the bar by releasing a major update to Refactor! Pro. That's right, Refactor! Pro 3.0 is now available and ships with 150 refactorings for C#, Visual Basic, C++, ASP .NET, XAML, and even JavaScript. The future is looking very bright indeed!

posted on Friday, December 28, 2007 12:53:10 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Thursday, December 27, 2007

Bells

JustinKohnen: @dcampbell: um... Christmas is over dude ;)

That was posted on Twitter today when I announced that I was working on this very blog entry. Well, I've got news for Mr. Justin "X-mas-Hater" Kohnen. X-mas isn't over until the fat... uhhh... lady sings. (Hmmm... that worked out much better in my head.)

While X-mas day has come and gone, the holiday season continues. I have enough verses left in my song to ensure that our merry-making runs all the way 'til the new year.

"On the eighth day of X-mas my true love (DevExpress) gave to me..."

Bread-and-Butter Refactorings in Query Expressions

Since LINQ is such a big part of what C# 3.0 and Visual Basic 9 are all about, I thought that showing two more examples of refactorings that can be used in query expressions would be useful. The refactorings we'll look at do not target query expressions specifically. Instead, these are pre-existing, bread-and-butter refactorings that have been updated to support query expressions properly.

What's a "bread-and-butter refactoring" you ask? It's one of those refactorings that you can't live without—a part of your everyday arsenal. It's important to know that these crucial refactorings work with the latest and greatest language features.

OK, let's get started!

public static int SumOfEvenSquares(int count)
{
  return (from number in Enumerable.Range(1, count)
          where (number % 2) == 0
          select number * number).Sum();
}

There are a number of refactorings that we could apply to the LINQ code above. First, let's use Introduce Local to generate a new local variable assigned to the query expression. This is easy enough to do. Just select the query expression, press the Refactor key (CTRL+` by default), choose Introduce Local, and press ENTER. Below is a screenshot of the preview hint for Introduce Local.

Introduce Local Preview Hint

The More You Know
If you are unfamiliar with Refactor! Pro's preview hints, they are sort of like windows into the future. A preview hint shows what a refactoring will do before you apply it. This feature provides the advantage you need to refactor your code with confidence.

After naming the new local variable, our refactored code looks like so:

public static int SumOfEvenSquares(int count)
{
  IEnumerable<int> evenSquares = from number in Enumerable.Range(1, count)
                                 where (number % 2) == 0
                                 select number * number;
  return evenSquares.Sum();
}

View Screencast of Introduce Local in Action!

I would be remiss if I didn't mention that there is another way to use Introduce Local. In addition to pressing the Refactor key, it is also possible to apply the refactoring using cut-and-paste. 99% of the time, when cutting an expression to the clipboard and pasting it within the same method on an empty line above the cut location, the user's intention is to create a local variable assigned to that expression. Refactor! Pro takes advantage of this knowledge to anticipate the user's intent and automatically apply Introduce Local.

View Screencast of Introduce Local Using Cut-And-Paste!

One of the red flags that some have raised against query expressions is their potential to cause code duplication. For example, the expressions in the where and select clauses from the sample code above really should be extracted to new methods. That way, we promote code reuse. If not, we are doomed to write the same tiny, bite-sized expressions over and over. Fortunately, Refactor! Pro's Extract Method refactoring works perfectly on these expressions. With Extract Method, we can easily turn the code above into:

private static IEnumerable<int> GetNaturals(int count)
{
  return Enumerable.Range(1, count);
}
private static bool IsEven(int number)
{
  return (number % 2) == 0;
}
private static int Square(int number)
{
  return number * number;
}
public static int SumOfEvenSquares(int count)
{
  IEnumerable<int> evenSquares = from number in GetNaturals(count)
                                 where IsEven(number)
                                 select Square(number);
  return evenSquares.Sum();
}

Believe it or not, using Refactor! Pro, I'm able to produce that code in just 42 keystrokes—including 23 keystrokes for the method names and 12 for navigation and selection. That means that only seven keystrokes are actually needed to apply three Extract Method refactorings!

Curious? View the Screencast of Extract Method in Action!

Finally, I must mention that Extract Method can be used with cut-and-paste just like Introduce Local. That's right, you can cut code to the clipboard and paste it on an empty line outside of a method. Extract Method will take over. Again, Refactor! Pro is working hard to anticipate your intentions.

View the Screencast of Extract Method Using Cut-And-Paste!

And thus ends the eighth verse of my song. Today we've looked at how two bread-and-butter refactorings, Introduce Local and Extract Method, can be used within LINQ expressions. The coolest thing is that all of the screencasts were recorded using Visual Studio 2008. They aren't mock ups of future features. These refactorings work with query expressions this very minute!

My Visual Basic friends might be a little worried because I didn't show these refactorings working in Visual Basic. Well, rest assured, the refactorings work fine. In fact, they work using the same keystrokes!

Now, that's what I call an X-mas present.

posted on Thursday, December 27, 2007 3:38:20 PM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Wednesday, December 26, 2007

Presents

Season's greetings! We're halfway through my X-mas carol describing how Refactor! Pro can be used to leverage the new features of Visual Studio 2008. Today, I'm sharing a little more Refactor! Pro love by demonstrating a refactoring that literally can save minutes of menial coding. That's right, minutes. Interested? OK, just let me clear my voice...

"On the seventh day of X-mas my true love (DevExpress) gave to me..."

Create Backing Store

A couple of days ago, I showed how Refactor! Pro can transform properties into C# 3.0 Auto-Implemented Properties. However, sometimes the opposite is needed. We need a way to convert from an auto-implemented property to a standard property and field. Consider the following code:

using System;
using System.Drawing;

namespace TwelveDaysOfXmas
{
  class Present
  {
    public Color Color1 { get; set; }
    public Color Color2 { get; set; }
  }
}

Suppose that we want to add logic to both the Color1 and Color2 properties to ensure that they can't be set to the same value. Now, imagine how much effort that would take. An awful lot of keystrokes are needed to get to the code below.

using System;
using System.Drawing;

namespace TwelveDaysOfXmas
{
  class Present
  {
    private Color m_Color1;
    public Color Color1
    {
      get { return m_Color1; }
      set
      {
        if (m_Color2 == value)
          return;
        m_Color1 = value;
      }
    }
    private Color m_Color2;
    public Color Color2
    {
      get { return m_Color2; }
      set
      {
        if (m_Color1 == value)
          return;
        m_Color2 = value;
      }
    }
  }
}

Fortunately, Refactor! Pro provides a refactoring, called Create Backing Store, which converts an auto-implemented property into a standard property with a field backing store. In other words, it transforms this...

public Color Color1 { get; set; }

...into this.

private Color m_Color1;
public Color Color1
{
  get
  {
    return m_Color1;
  }
  set
  {
    m_Color1 = value;
  }
}

That's pretty close to what we want. With the help of two other refactorings, Introduce Setter Guard Clause and Collapse Accessor, we can continue to manipulate the property to get the code below.

private Color m_Color1;
public Color Color1
{
  get { return m_Color1; }
  set
  {
    if (m_Color1 == value)
      return;
    m_Color1 = value;
  }
}

Now we just have to make a minor edit to the guard clause and we're done.

View Screencast of These Refactorings in Action!

And that concludes my verse for today. Remember that the features I'm showing you are available for download this very second. So, if you're tired of waiting for <whisper>the other tool</whisper> to get its act together, Refactor! Pro can have you running laps through Visual Studio 2008 in no time.

posted on Wednesday, December 26, 2007 12:52:42 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Tuesday, December 25, 2007

Presents

Merry X-mas friends! It is indeed X-mas day, and I have returned with a special gift for you. Today, I'm doing my part to bring peace on earth and goodwill toward developers by showing one way that Refactor! Pro can simplify the dreaded lambda expressions. I'll achieve this by showing three refactorings which can be used together to transform some very C-ish code into modern C# 3.0 code.

And now, it's time to continue my anthem.

There's a hush. All is quiet. Then, in the silence, a still, small voice is heard. It grows louder and louder until...

"On the sixth day of X-mas my true love (DevExpress) gave to me..."

Compress to Lambda Expression

I'm not exactly sure why, but every time that I mention "lambda expressions" to developers, their faces show confusion and terror. My guess is that this reaction is caused by one of three things:

  1. A fear of Greek letters (i.e. "lambda")
  2. A fear of all things pointy (i.e. the => operator that lambda expressions bristle with.)
  3. A fear of all things functional (i.e. passing functions around like candy.)

It's for these reasons that I'll demonstrate a couple of other refactorings first. We'll work our way up to lambda expressions. Let's start with something more familiar.

using System;
using System.Collections.Generic;

namespace TwelveDaysOfXmas
{
  class CompressToLambdaExpression
  {
    public static int SumList(List<int> list)
    {
      int sum = 0;
      for(int i = 0; i < list.Count; i++)
        sum += list[i];
      return sum;
    }
  }
}

The code above is an example of the sort of imperative code that we write all of the time. What do I mean by "imperative?" Well, it's like writing a recipe for the computer—describing, in excruciating detail, the steps to solve a problem. There's nothing terribly wrong with that. After all, it's how our computer processors work. They execute a list of instructions—one at a time. However, there is another way that this code can be written.

On the other side of the coin from imperative code is declarative code. Declarative code describes what should be done instead of specifically how it should be done. Writing code declaratively has many potential benefits over the imperative style.

  1. It can be easier to read.
  2. It can be easier for the compiler/runtime to optimize.
  3. It can promote code reuse.

We can write the above code a bit more declaratively by using a foreach loop.

using System;
using System.Collections.Generic;

namespace TwelveDaysOfXmas
{
  class CompressToLambdaExpression
  {
    public static int SumList(List<int> list)
    {
      int sum = 0;
      foreach (int number in list)
        sum += number;
      return sum;
    }
  }
}

That's better! To save keystrokes, Refactor! Pro provides a For to ForEach refactoring that easily performs this conversion. Here's how the preview hint for this refactoring looks:

For to ForEach Preview Hint

Another declarative possibility is to call the List<T>.ForEach method instead using of a foreach loop. In that case, we would pass an anonymous delegate to the method as the body of the loop like so:

using System;
using System.Collections.Generic;

namespace TwelveDaysOfXmas
{
  class CompressToLambdaExpression
  {
    public static int SumList(List<int> list)
    {
      int sum = 0;
      list.ForEach(delegate(int number)
      {
        sum += number;
      });
      return sum;
    }
  }
}}

In a declarative fashion, the above code states, "loop through the entire list, and execute this function (delegate) for each item in the list." A powerful feature of the anonymous delegate is that it references a variable (sum) outside of the delegate body, producing a closure. (For more information on closures, check out this article.)

Of course, Refactor! Pro provides a refactoring that renders this transformation trivial: Introduce ForEach Action. The screenshot below shows the preview hint for this refactoring.

Introduce ForEach Action Preview Hint

Now, some of you might be saying, "Whoa! That anonymous delegate sure is an ugly little spud1." You're right, it is. Enter the lambda expression.

I don't want to present an entire history of lambda expressions here, but you should understand that they pre-date computers entirely. So, if you've been wondering where these crazy new things came from, know that they really aren't crazy "new" things. Lambda expressions have been around since the 1930s.

A C# lambda expression is really just an anonymous delegate on steroids. It retains all of the functionality of an anonymous delegate but adds conciseness, better type inference and even pseudo-meta-programming via expression trees.

Using a lambda expression is straight-forward, if a little funky:

using System;
using System.Collections.Generic;

namespace TwelveDaysOfXmas
{
  class CompressToLambdaExpression
  {
    public static int SumList(List<int> list)
    {
      int sum = 0;
      list.ForEach(number => sum += number);
      return sum;
    }
  }
}

If this is the first time that you've seen a lambda expression in the wild, compare it with the anonymous delegate that we used before. The parameters are declared to the left of the => operator, and the body is declared to the right. The compiler works out the types of the parameters so there's no need to specify them.

Of course, my X-mas present for you today is another refactoring: Compress to Lambda Expression. This refactoring (available now) converts anonymous delegates into lambda expressions, saving dozens of keystrokes and head scratches. Again, here is the preview hint to show what this refactoring does:

Compress to Lambda Expression Preview Hint

View Screencast of These Refactorings in Action!

As always, I'm demonstrating features of Refactor! Pro that can be used to leverage the new features in Visual Studio 2008 right now. In fact, all of the refactorings above have been shipping for several months. In other words, these aren't in some super-secret beta. They have been released.

As another refactoring goodie has been successfully unwrapped, it's time to take my leave of you. Until tomorrow, have a warm and happy X-mas!

1Ray Stanz, Ghostbusters.

posted on Tuesday, December 25, 2007 9:31:26 AM (Pacific Standard Time, UTC-08:00)  #    Comments [2]

kick it on DotNetKicks.com
 Monday, December 24, 2007

Nutcracker

'Twas the night before X-mas, when all through the house,
Not a creature was stirring, not even a mouse;
The stockings were hung by the chimney with care,
In hopes that DevExpress soon would be there;
The children were nestled all snug in their beds,
While visions of
Refactor! Pro danced in their heads.

Ho, ho, ho! I'm back to stuff your stockings with another feature of Refactor! Pro that lets you leverage Visual Studio 2008 on this fine X-mas Eve.

But wait! Who's that knocking at your front door? Why it's a group of carolers, here to sing a noël for us. Shhh! They're about to begin.

"On the fifth day of X-mas my true love (DevExpress) gave to me..."

Convert to Auto-Implemented Property

One of the tastiest syntactic sugar cookies that has been added to C# 3.0 is Auto-Implemented Properties. This feature allows C# developers to define properties far more concisely than before. Here's how we used to define properties in C# 2.0:

using System;
using System.Drawing;

namespace TwelveDaysOfXmas
{
  class Present
  {
    private Color m_Color;
    private bool m_HasBow;

    public Present(Color color, bool hasBow)
    {
      m_Color = color;
      m_HasBow = hasBow;
    }

    public Color Color
    {
      get { return m_Color; }
    }
    public bool HasBow
    {
      get { return m_HasBow; }
      set { m_HasBow = value; }
    }
  }
}

Whew! That's a lot of effort! Thanks to auto-implemented properties, we can now define our properties like so:

using System;
using System.Drawing;

namespace TwelveDaysOfXmas
{
  class Present
  {
    public Present(Color color, bool hasBow)
    {
      Color = color;
      HasBow = hasBow;
    }

    public Color Color { get; private set; }
    public bool HasBow { get; set; }
  }
}

Convert to Auto-Implemented Property is a refactoring that can be used to change the first example into the second example. Check out the preview hint below to see everything that this refactoring will do for you.

Convert to Auto-Implemented Property Preview Hint

  1. It removes the field that serves as the backing store for the property.
  2. It converts all field references into references to the property.
  3. It replaces the property with an auto-implemented version. I should point out that the refactoring intelligently generates an auto-implemented property with a private setter because the property is read-only (write-only properties are handled similarly).
  4. There is also a Convert to Auto-Implemented Property (convert all) refactoring which will transform all of the properties in the current type.

That's all there is to it! This refactoring does exactly what you expect it to do, and using it will save you dozens of keystrokes.

Unfortunately, our Visual Basic friends aren't feeling the love. You see, auto-implemented properties is a C# 3.0-only feature that did not make it into Visual Basic 9. However, it would be shameful to leave any developer out in the cold. At the request of the Visual Basic team, we've added a new feature that provides the illusion of auto-implemented properties in Visual Basic.

VB Property Collapse 1

The above screenshot shows what the code looks like as it is being edited. As you can see, no changes have been made yet. However, once the editor caret leaves the property, the field and property automatically collapse onto one line:

VB Property Collapse 2

View Screencast of VB Property Collapse in Action!

That sleight-of-hand helps VB code appear more concise. I hope this will help our Visual Basic friends feel a warm glow this holiday season.

And with that, I must bid you farewell. Until next time...

He spoke not a word, but went straight to his work,
And filled all the stockings; then turned with a jerk,
And laying his finger aside of his nose,
And giving a nod, up the chimney he rose.
He sprang to his sleigh, to his team gave a whistle,
And away they all flew, like the down of a thistle:
But I heard him exclaim, as he drove out of sight—
Merry X-mas to all, and to all a good night.

posted on Monday, December 24, 2007 7:39:36 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Sunday, December 23, 2007

Santa Cat

Feliz Navidad my mistletoe aficionados! I've just finished warming up my voice and am ready to continue my aria of Refactor! Pro support for Visual Studio 2008. Ready or not, here we go!

And a one, and a two, and a one, two, three, four!

"On the fourth day of X-mas my true love (DevExpress) gave to me..."

Rename Works In Query Expressions

Today, instead of examining a brand new feature, we'll see how a pre-existing refactoring handles the new features of C# 3.0 and Visual Basic 9. Adding support for new language features involves much more than simply creating a handful of new refactorings—all existing refactorings must be updated as well. With Refactor! Pro, you can be confident that we've done our homework and provided support for Visual Studio 2008 across the entire product.

Of all the refactorings available to me, I use Rename the most frequently. This is due to the fact that I use Refactor! Pro to shape my code while I write it. Often, while coding a solution, I find that a variable's meaning is no longer consistent with its name. When this happens, Rename allows me to change the variable's name efficiently and accurately. In fact, I've used Rename so often that I've grown to trust it implicitly.

Rename doesn't let me down when I'm working with a C# 3.0 query expression. With the editor caret positioned on the identifier of the from clause, I can press the Refactor key (CTRL+` on my machine), and Rename kicks in, highlighting the active identifier and all its references.

Rename in C# Query Expression (start)

At this point, I can just type the new variable name. All references are updated in real time.

Rename in C# Query Expression (end)

View Screencast of Rename in Action!

Rename also works perfectly in an equivalent Visual Basic query expression (using fancy Aggregate syntax). Again, it's as easy as pressing the Refactor Key...

Rename in VB Query Expression (start)

...and typing the new variable name.

Rename in VB Query Expression (end)

Neat!

The moral of today's verse is that Refactor! Pro offers deep support for Visual Studio 2008 in every refactoring. You can rest assured that all refactorings just work as expected. And most importantly, they are working this very minute. Not tomorrow. Not sometime in January. Now.

Have a Merry X-mas!

posted on Sunday, December 23, 2007 12:22:04 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Saturday, December 22, 2007

Nutcracker

Welcome back my 'nog-froth mustachioed friends! I've returned with another helping of Refactor! Pro goodness for Visual Studio 2008. One scrooge commented that the last present was a little weak, so I've decided to give a bigger gift this time. However, I will be saving some of my bestest presents for the very end.

So, sit back, relax and take out your ear plugs as I serenade you with my third verse.

"On the third day of X-mas my true love (DevExpress) gave to me..."

Name Anonymous Type

Of all the new features in C# 3.0 and Visual Basic 9, Anonymous Types is one of the most convenient. This feature allows the user to create new objects "on the fly," without providing type definitions for them. For example:

var person = new { Name = "St. Nick", Age = "Really Old" };
Console.WriteLine(person.Name);

When the C# compiler encounters the code above, it generates a new type with two string properties: Name and Age.

This powerful new feature is not without limitations. Because anonymous types have no accessible type name (they're anonymous - duh!), they can only be referenced by variables that are implicitly-typed. This becomes very frustrating when using anonymous types in other natural ways.

public static ??? CreatePerson()
{
  return new { Name = "St. Nick", Age = "Really Old" };
}

What should I fill in for ??? in the code above? One possibility is to use object. However, if I do that, how do I access the properties from client code? Reflection? An awkward casting helper?

Recently, this very problem was hashed out on the MSDN forums. The general consensus was, when you want to expose an anonymous type in an API (e.g. return an anonymous type from a method), swap it out for a defined type. However, defining a new type that matches an anonymous type is cumbersome. Thankfully, Refactor! Pro can step in and do this work for you. When the Name Anonymous Type refactoring is applied to the anonymous type above, the following class is generated:

[DebuggerDisplay("\\{ Name = {Name}, Age = {Age} \\}")]
public sealed class Person: IEquatable<Person>
{
  private readonly string m_Name;
  private readonly string m_Age;

  public Person(string name, string age)
  {
    m_Name = name;
    m_Age = age;
  }

  public override bool Equals(object obj)
  {
    if (obj is Person)
      return Equals((Person)obj);
    return false;
  }
  public bool Equals(Person obj)
  {
    if (!EqualityComparer<string>.Default.Equals(m_Name, obj.m_Name))
      return false;
    if (!EqualityComparer<string>.Default.Equals(m_Age, obj.m_Age))
      return false;
    return true;
  }
  public override int GetHashCode()
  {
    int hash = 0;
    hash ^= EqualityComparer<string>.Default.GetHashCode(m_Name);
    hash ^= EqualityComparer<string>.Default.GetHashCode(m_Age);
    return hash;
  }
  public override string ToString()
  {
    return String.Format("{{ Name = {0}, Age = {1} }}", m_Name, m_Age);
  }

  public string Name
  {
    get
    {
      return m_Name;
    }
  }
  public string Age
  {
    get
    {
      return m_Age;
    }
  }
}

View Screencast of Name Anonymous Type in Action!

You might be thinking, "Wow! That's a lot of code! Is all of that really necessary?" The answer is, yes, all of that code is necessary to produce a type definition that is equivalent to the subtle features of an anonymous type. In C#, anonymous types are immutable so we must generate read-only fields and properties. In addition, the equality and identity of anonymous types are explicitly defined so they can be compared with one another. In other words, C# anonymous types have value-type semantics. The following code sample might clarify this:

var person1 = new
{
  Name = "Dustin Campbell",
  Age = "32"
};

var person2 = new
{
  Name = "Dustin Campbell",
  Age = "32"
};

var person3 = new
{
  Name = "Dustin's Trophy Wife",
  Age = "Undisclosed (but probably really, really young)"
};

Console.WriteLine(person1.Equals(person2));
Console.WriteLine(person2.Equals(person3));

Because of the value-type characteristics of anonymous types, the above code outputs the following to the console.

True
False

Of course, if Name Anonymous Type is applied, the same output is produced.

Traditionally, the Visual Basic team likes to make life hard for us, and anonymous types are no exception. Contrary to C#, the Visual Basic compiler generates mutable anonymous types. In addition, Visual Basic allows for partially-mutable anonymous types when the Key keyword is applied. (This is further proof that C# and Visual Basic have very different agendas and destinies.) Fortunately, Name Anonymous Type is intelligent enough to handle these differences.

Dim person = New With {.Name = "St. Nick", .Age = "Really Old"}

When applied to the above code, Name Anonymous Type generates a new Person class like so:

<DebuggerDisplay("\{ Name = {Name}, Age = {Age} \}")> _
Public NotInheritable Class Person
  Private m_Name As String
  Private m_Age As String

  Public Sub New(ByVal name As String, ByVal age As String)
    m_Name = name
    m_Age = age
  End Sub

  Public Overrides Function ToString() As String
    Return String.Format("{{ Name = {0}, Age = {1} }}", m_Name, m_Age)
  End Function

  Public Property Name() As String
    Get
      Return m_Name
    End Get
    Set(ByVal value As String)
      m_Name = value
    End Set
  End Property
  Public Property Age() As String
    Get
      Return m_Age
    End Get
    Set(ByVal value As String)
      m_Age = value
    End Set
  End Property
End Class

To be consistent with the reference-type semantics of Visual Basic anonymous types, Name Anonymous Type produces a mutable class. Gone are the overrides to Equals() and GetHashCode(). In addition, the properties are read-write. It's this sort of language independence that makes Refactor! Pro a choice tool for Visual Studio 2008 development.

And that wraps up another verse in my holiday sing-a-long! Remember that the features I am showing can be used right now. There's no need to wait for some forthcoming beta. You can use them today. Until next time...

posted on Saturday, December 22, 2007 8:35:00 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Friday, December 21, 2007

Fireplace

Season's greetings! Welcome back for another dose of Yuletide cheer! Yesterday, I sang to you about one way in which Refactor! Pro can be used to leverage the new features of C# 3.0 and Visual Basic 9 right now. Today, I'm back with another verse to warm your hearts this holiday season.

So, strike up the band! Rouse the drunken carolers! It's time to go a wassailing once more.

"On the second day of X-mas my true love (DevExpress) gave to me..."

Make Explicit

Like its sister refactoring, Make Explicit enables developers to manipulate implicitly-typed local variables. However, it performs the opposite operation as Make Implicit. It converts implicitly-typed local variables to explicit ones. In other words, Make Explicit will transform the following code:

var number = 42ul;

Like so:

ulong number = 42ul;

Make Explicit must do a great deal of work to determine the type of the expression that an implicitly-typed local variable is assigned to. Consider the following code (which I found lurking in some corner of the 'net):

using System;
using System.Linq;
using System.ServiceProcess;

namespace TwelveDaysOfXmas
{
  class MakeExplicit
  {
    static void DisplayServices()
    {
      var services = from service in ServiceController.GetServices()
                     where service.Status == ServiceControllerStatus.Running
                     orderby service.ServiceName ascending
                     select service;

      foreach (ServiceController aService in services)
      {
        Console.WriteLine(aService.ServiceName);
      }

      Console.ReadLine();
    }
  }
}

In order to determine the type of services, Make Explicit must have a full understanding of LINQ. First, it must transform the query expression into the appropriate extension methods and lambda expressions like so:

var services = ServiceController.GetServices()
                 .Where(service => service.Status == ServiceControllerStatus.Running)
                 .OrderBy(service => service.ServiceName)

Next, Make Explicit must be able to resolve the extension methods and infer the types of the lambda expressions. Once this is done, the type of the expression can finally be determined. That's an awful lot of work, but it's required to ensure that the type is inferred accurately. Fortunately, Make Explicit executes all of this with blazing speed and infers the correct type:

IOrderedEnumerable<ServiceController> services = from service in ServiceController.GetServices()
                                                 where service.Status == ServiceControllerStatus.Running
                                                 orderby service.ServiceName ascending
                                                 select service;

View Screencast of Make Explicit in Action! (#1)

If you have any doubt that Make Explicit is really doing this much work behind the scenes, try commenting out the orderby clause. Make Explicit will infer the correct type even after the query expression has changed:

IEnumerable<ServiceController> services = from service in ServiceController.GetServices()
                                          where service.Status == ServiceControllerStatus.Running
                                          //orderby service.ServiceName ascending
                                          select service;

View Screencast of Make Explicit in Action! (#2)

Finally, I should mention that Make Explicit works just as handily with Visual Basic.

Dim services = From service In ServiceController.GetServices() _
               Where service.Status = ServiceControllerStatus.Running _
               Order By service.ServiceName Ascending

In the above code, Make Explicit properly infers the type of services as IOrderedEnumerable<ServiceController>. Awesome.

One last closing thought: some of you might be thinking right now, "Why would I want to do this? Aren't implicitly-typed local variables better?" There are a few scenarios in which Make Explicit is useful:

  1. Specifying the type name sometimes makes code easier to read.
  2. It simplifies porting code backwards (e.g. to compile in an earlier version of Visual Studio).
  3. It can be helpful for learning and understanding code.

For these reasons, Make Explicit takes its rightful place among the refactorings that support Visual Studio 2008.

"And a partridge in a pear tree..."

And so concludes today's verse. It's time to settle back with a warm mug of spiked eggnog and kick up your feet. Join me tomorrow as we take a peek at another way in which Refactor! Pro brings the X-mas love.

posted on Friday, December 21, 2007 10:44:12 AM (Pacific Standard Time, UTC-08:00)  #    Comments [3]

kick it on DotNetKicks.com
 Thursday, December 20, 2007

Fireplace

Gentle readers, in the spirit of X-mas, I'd like to sing you a carol. This jolly tune (based on a popular old English carol) enumerates ways that Refactor! Pro can warm your installation of Visual Studio 2008 this holiday season. In contrast to some of our... ahem... <whisper>competition</whisper>, the features I'll be showing can be used today. In fact, most of these features have been shipping since Visual Studio 2008 was still a wee child known by its code name, Orcas.

But, hey, enough of my yammering! Stoke the fire and put on a kettle! Let the merry-making begin!

"On the first day of X-mas my true love (DevExpress) gave to me..."

Make Implicit

Visual Studio 2008 introduced a welcome addition to both the C# and Visual Basic languages: implicitly-typed local variables. While this feature is necessary to properly support another feature, anonymous types, it can also be used to enhance the readability of client code—especially when generic types are being used. Consider the following code:

private static Dictionary<string, Guid> BuildIdTable()
{
  Dictionary<string, Guid> map = new Dictionary<string, Guid>();

  // Fill map with entries...

  return map;
}

That sort of code can be a bit frustrating. Dictionary<TKey, TValue> is extremely powerful, but can be awkward to use. The developer is forced to fully declare the type name (which is often quite long) on both the left and right sides of the local variable declaration. Thankfully, an implicitly-typed local variable can alleviate this problem:

private static Dictionary<string, Guid> BuildIdTable()
{
  var map = new Dictionary<string, Guid>();

  // Fill map with entries...

  return map;
}

Now for the really good news: Refactor! Pro provides Make Implicit, a refactoring which easily converts explicitly-declared local variables to implicit ones. Check out the preview hint for Make Implicit:

View Screencast of Make Implicit in Action!

Of course, like most of our refactorings, Make Implicit works in Visual Basic as well.

Some critics might be thinking, "What's the point? It just deletes text and inserts a keyword! I could write a macro to do that!" Well, before those skeptics get too comfortable with their new macro, consider what Make Implicit must do with code like the following:

ulong number = 42;

If Make Implicit were simply to swap ulong for var, there would be a serious problem. Instead of ulong, the type of number would be inferred as int, changing the meaning of the code. To fix this problem, a minor adjustment is made to prevent shooting the code in its proverbial foot.

var number = 42ul;

So, throw your macro away! Let Make Implicit handle the edge cases intelligently.

Ho, ho, ho! That's quite a gift under the tree! Come back tomorrow when I continue my jaunty tune and look at another Visual Studio 2008-specific refactoring that is available to you today: Make Explicit.

posted on Thursday, December 20, 2007 10:31:39 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Wednesday, December 19, 2007
Last night, I had the pleasure of presenting my Functional C# talk to the West Michigan .NET User Group. It was truly a joy. The group is sharp, attentive and engaging. In addition, their venue is very cool. WMNUG meets at the Watermark Country Club in Grand Rapids, MI, where they get gourmet pizzas delivered to them (no fast-food pizza for these guys!) and have access to a cash bar. Needless to say, the presentation became a bit more "spontaneous" as I consumed my fill of a wonderful brown ale. Thanks to my good friend Chris Woodruff for supplying me with the beer.

Speakers: If you're looking for a great place to present, this is it.

posted on Wednesday, December 19, 2007 12:05:16 PM (Pacific Standard Time, UTC-08:00)  #    Comments [2]

kick it on DotNetKicks.com
 Friday, November 23, 2007
Visual Studio 2008's multi-targeting support for compiling projects to different versions of the .NET Framework is very powerful. Multi-targeting is a compelling feature because it enables users to continue working on solutions that target .NET Framework 2.0 and 3.0 while upgrading to the latest and greatest IDE. What isn't obvious is that all projects, regardless of target, are compiled with the C# 3.0 compiler. That means users can employ many of the new C# 3.0 language features in legacy projects. The only language features that can't be used are those that require library support from .NET Framework 3.5, in essence, LINQ, Expression Trees and Extension Methods. Implicitly-typed local variables, lambda expressions, auto-implemented properties, object and collection initializers, and anonymous types are all fair game. It's sort of like having C# 3.0-lite or C# 2.5.

Interestingly, it has recently been discovered that even Extension Methods can be used in projects targeting .NET Framework 2.0 and 3.0. All that must be done to enable this support is to create a new System.Runtime.CompilerServices.ExtensionAttribute.

using System;

namespace System.Runtime.CompilerServices
{
  public class ExtensionAttribute: Attribute
  {
  }
}

This trick does have flaws. There are potential scoping issues that occur when an assembly containing a custom System.Runtime.CompilerServices.ExtensionAttribute is referenced by a project that targets .NET Framework 3.5. A compiler warning is generated stating that "the predefined type 'System.Runtime.CompilerServices.ExtensionAttribute' is defined in multiple assemblies in the global alias." However, this is only a minor irritation. In my tests, Extension Methods still worked properly despite the warning.

The ability to use C# 3.0 features in .NET Framework 2.0 or 3.0 projects is very powerful. It helps users get comfortable with the new syntax without having to upgrade projects to .NET Framework 3.5. Viva la C# 2.5!

posted on Friday, November 23, 2007 7:29:08 AM (Pacific Standard Time, UTC-08:00)  #    Comments [5]

kick it on DotNetKicks.com
 Tuesday, November 13, 2007
While exploring F#, I've grown increasingly impressed by the libraries that ship with it. One of the main purposes of the libraries is to provide underlying support for the language itself. In addition, they contain important modules and classes necessary for functional programming (e.g. immutable List and Map types). However, the most practical aspect of these libraries to me is the rich set of APIs that facilitate using the .NET Framework in a more functional way. These APIs are often directly portable to C#. Let's look at a simple example.

The following C# code is typical of how we might create an array containing the natural numbers from 1 to 20:

int[] a = new int[20];
for (int x = 0; x < a.Length; x++)
  a[x] = x + 1;

There's nothing special about that code. It's representative of the sort of thing that we write all the time. However, it won't fly in the functional world because it's written in an imperative style. That is, the code specifies the exact steps that should be taken to create and initialize the array:

  1. Create a new int array of 20 elements.
  2. Initialize a new indexer variable, x, to 0.
  3. Check to see that x is less than the length of the array. If it isn't, STOP.
  4. Assign the value of the array element at index x to the result of x + 1.
  5. Increment x.
  6. GO BACK to step 3. Repeat as necessary.

In contrast, the F# libraries provide a special module, Array, for manipulating single-dimensional .NET arrays in a more functional style. (Array2 and Array3 are also available for manipulating two- and three-dimensional arrays respectively.) Using the Array module, the C# code above could be translated to F# like so:

let a = Array.init 20 (fun x -> x + 1)

Instead of a specific code recipe, this F# code says (in a more declarative fashion), "create an array of 20 elements, and use this function to initialize each element." An interesting feature of the F# version is that the type of the array is never declared. Because the compiler can infer that the result of the passed function (fun x -> x + 1) will be an int, "a" must be an int array.

To me, this code is beautiful. In addition, it is declarative instead of imperative; it describes what should be done but doesn't dictate exactly how it should be done. When I see such elegant code, I immediately start trying to figure out which of its aspects could be used to improve the code in my daily C# work. Here's how we might "borrow" the F# "Array.init" function in C#:

public static class ArrayEx
{
  public delegate T CreateItem<T>(int index);
 
  public static T[] Create<T>(int length, CreateItem<T> createItem)
  {
    if (length < 0)
      throw new ArgumentOutOfRangeException("length");
 
    if (length == 0)
      return new T[0];
 
    T[] result = new T[length];
    if (createItem != null)
    {
      for (int i = 0; i < length; i++)
        result[i] = createItem(i);
    }
    return result;
  }
}

With this function defined, we can rewrite our array creation sample declaratively using C# 3.0 syntax.

var a = ArrayEx.Create(20, x => x + 1);

Notice that this code takes advantage of the C# compiler's type inference in the same way that the F# sample does. Sweet!

Let's take a look at another example. Suppose we want to iterate through all of the elements in our int array and output each element's value to the console. We have a few of options available to us. First, there's the familiar for-loop approach:

for (int x = 0; x < a.Length; x++)
  Console.WriteLine(a[x]);

Second, there's the more declarative foreach-loop:

foreach (int val in a)
  Console.WriteLine(val);

Finally, the underused "Array.ForEach" BCL method is also a possibility:

Array.ForEach(a, val => Console.WriteLine(val));

In addition, because "Console.WriteLine" has an overload which accepts a single int parameter, we can rewrite the previous code without a lambda expression:

Array.ForEach(a, Console.WriteLine);

Now, for the monkey wrench. Suppose we want to print the index of each element in the array along with the value. With this added requirement, the for-loop is our most attractive choice because the indexer variable is already built in. The other two options would require awkwardly creating an indexer variable and explicitly incrementing it. This additional code looks especially ugly with the "Array.ForEach" option.

int x = 0;
Array.ForEach(a, val => Console.WriteLine("{0}: {1}", x++, val));

Nasty.

How might we handle this in F#? Simple. F# provides an API designed to iterate an array with an index.

Array.iteri (fun x value -> printfn "%i: %i" x value) a

Like the BCL's "Array.ForEach" method, F#'s "Array.iteri" iterates through an array and applies the given function to each element. The difference is that the function to be applied includes an additional parameter representing the element's index in the array.

NeRd Note
Curious about why the parameter ordering of the F# "Array.iteri" API places the function to be applied before the array to be iterated? Isn't that backwards? Wouldn't it make more sense to move the array parameter to the first position? Nope. The parameter ordering is intentional.

Unless specified, F# functions are implicitly curried. Hence, parameters are usually ordered to take advantage of partial application. If the parameters of "Array.iteri" were reordered, we could not easily use partial application to build useful functions from it.
let print = Array.iteri (fun x value -> printfn "%i: %i" x value)

print a
Besides, if passing "a" as the last parameter is awkward, we can always pass it with the F# pipeline operator.
a |> Array.iteri (fun x value -> printfn "%i: %i" x value)
Make sense? OK. Take a deep breath...

Using F#'s "Array.iteri" as a model, we can define an equivalent function in C#.

public static class ArrayEx
{
  public delegate void IndexedAction<T>(int index, T item);
 
  public static void Iterate<T>(T[] array, IndexedAction<T> action)
  {
    if (array == null)
      throw new ArgumentNullException("array");
    if (action == null)
      throw new ArgumentNullException("action");

    if (array.Length <= 0)
      return;

    int lower = array.GetLowerBound(0);
    int upper = array.GetUpperBound(0);

    for (int i = lower; i <= upper; i++)
      action(i, array[i]);
  }
}

Now we can iterate our array and output the index and value of each element to the console with one line of code!

ArrayEx.Iterate(a, (x, i) => Console.WriteLine("{0}: {1}", x, i));

Since we're using C# 3.0, we can declare "ArrayEx.Iterate" as an extension method to make the client code more readable.

a.Iterate((x, i) => Console.WriteLine("{0}: {1}", x, i));

In conclusion, using F# as a source of inspiration, it's easy to create APIs that enable more declarative C# code to be written. Do you have a cool declarative API that you've written for C# or VB? If so, I'd love to hear about it. Feel free to post your creations in the comments or email me directly.

posted on Tuesday, November 13, 2007 8:17:23 PM (Pacific Standard Time, UTC-08:00)  #    Comments [18]

kick it on DotNetKicks.com
 Friday, October 26, 2007
Lately, I've been spending some quality time with Microsoft's F# language. So far, I'm completely enamored with the brevity and clarity of the language. It just feels right to me.

I recently wrote up some articles on how one might use currying, partial application and function composition along with C# and delegates to produce the factorial function from two higher-order functions. The result of this labor is below.

static void Main()
{
  var reduce = HigherOrder.GetReduce<Int64>().Curry();
  var getProduct = reduce((x, y) => x * y)(1);

  var sequence = HigherOrder.GetSequence<Int64>().Curry();
  var naturalsFromOne = sequence(x => ++x)(1);

  var equals = HigherOrder.GetEquals<Int64>().Curry();

  var naturalsFromOneToX = HigherOrder.Compose(equals, naturalsFromOne);
  var factorial = HigherOrder.Compose(naturalsFromOneToX, getProduct);

  var factorialOf10 = factorial(10);

  Console.WriteLine("Factorial of 10 is {0:#,#}", factorialOf10);
}

That code is a truly magnificent beast. While it's academically interesting to torture delegates like this, it isn't all that fruitful when the language (i.e. C#, VB) doesn't really support these shenanigans. Try that in some production code and see how quickly you lose your development job.

As an exercise, here's how I might build factorial using the same techniques in F#:

#light

let getProduct = Seq.fold ( * ) 1
let naturalsFromOneToX n = [1 .. n]
let factorial = naturalsFromOneToX >> getProduct

printf "Factorial of 10 is %i" (factorial 10)

The first thing I should point out is that no delegates are used in this sample. F# natively supports functions as values so it's unnecessary to create delegates for them (and no, it doesn't create delegates under the covers). Secondly, functions are automatically curried in F#. You can declare functions so that they aren't curried, but that's really only useful if you're writing code that should be callable from other .NET languages. And finally, F# provides an operator (>>) for function composition.

To be fair, I should point out that the above implementation is pretty naive. It's not necessary to use function composition. This will suffice:

#light

let factorial n = Seq.fold ( * ) 1 [1 .. n]

printf "Factorial of 10 is %i" (factorial 10)

If compiled with fsc.exe, that code will print the following to the console:

Factorial of 10 is 3628800

That's great, but what if I try to calculate the factorial of 1000?

Factorial of 1000 is 0

Hmmm... what's going on here? Well, it turns out that the F# compiler inferred the type of "factorial" to be:

val factorial : int -> int

"int" maps to the standard .NET type, System.Int32, so this factorial function expects an Int32 and returns an Int32. However, Int32 isn't actually large enough to hold the factorial of 1000. This is a job for F#'s "bigint" type. "bigint" maps to the Microsoft.FSharp.Math.Types.BigInt type which can represent arbitrarily large integer values. With a few minor modifications, the factorial function can use "bigint," and the factorial of 1000 can be properly calculated.

#light

let factorial n = Seq.fold ( * ) 1I [1I .. n]

printf "Factorial of 1000 is %A" (factorial 1000I)

Now, the F# compiler infers the type of "factorial" to be:

val factorial : bigint -> bigint

And what does that program print to the console?

Factorial of 1000 is 40238726007709377354370243392300398571937486421071463254379
99104299385123986290205920442084869694048004799886101971960586316668729948085589
01323829669944590997424504087073759918823627727188732519779505950995276120874975
46249704360141827809464649629105639388743788648733711918104582578364784997701247
66328898359557354325131853239584630755574091142624174743493475534286465766116677
97396668820291207379143853719588249808126867838374559731746136085379534524221586
59320192809087829730843139284440328123155861103697680135730421616874760967587134
83120254785893207671691324484262361314125087802080002616831510273418279777047846
35868170164365024153691398281264810213092761244896359928705114964975419909342221
56683257208082133318611681155361583654698404670897560290095053761647584772842188
96796462449451607653534081989013854424879849599533191017233555566021394503997362
80750137837615307127761926849034352625200015888535147331611702103968175921510907
78801939317811419454525722386554146106289218796022383897147608850627686296714667
46975629112340824392081601537808898939645182632436716167621791689097799119037540
31274622289988005195444414282012187361745992642956581746628302955570299024324153
18161721046583203678690611726015878352075151628422554026517048330422614397428693
30616908979684825901254583271682264580665267699586526822728070757813918581788896
52208164348344825993266043367660176999612831860788386150279465955131156552036093
98818061213855860030143569452722420634463179746059468257310379008402443243846565
72450144028218852524709351906209290231364932734975655139587205596542287497740114
13346962715422845862377387538230483865688976461927383814900140767310446640259899
49022222176590433990188601856652648506179970235619389701786004081188972991831102
11712298459016419210688843871218556461249607987229085192968193723886426148396573
82291123125024186649353143970137428531926649875337218940694281434118520158014123
34482801505139969429015348307764456909907315243327828826986460278986432113908350
62170950025973898635542771967428222487575867657523442202075736305694988250879689
28162753848863396909959826280956121450994871701244516461260379029309120889086942
02851064018215439945715680594187274899809425474217358240106367740459574178516082
92301353580818400969963725242305608559037006242712434169090041536901059339838357
77939410970027753472000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000I

Awesome.

One last point: writing factorial in F# is completely unnecessary. It already exists.

#light

open Microsoft.FSharp.Math.BigInt

printf "Factorial of 1000 is %A" (factorial 1000I)
posted on Friday, October 26, 2007 12:02:36 PM (Pacific Standard Time, UTC-08:00)  #    Comments [3]

kick it on DotNetKicks.com
 Tuesday, October 23, 2007
In the seventh article of my series on functional programming ideas using C#, I build on the ideas of currying and partial application. In addition, I cover a new concept: function composition.
posted on Tuesday, October 23, 2007 6:43:45 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Friday, September 28, 2007

Recently, I presented an example of how closures can cause headaches when used in the context of LINQ expressions:

static class Program
{
  static void Main()
  {
    var filter = String.Empty;
 
    var query = from m in typeof(String).GetMethods()
                orderby m.Name
                where m.Name != filter
                select m.Name;
 
    foreach (var item in query)
    {
      Console.WriteLine(item);
      filter = item;
    }
  }
}

I want to state clearly that the example above is academic and not representative of how anybody should be writing LINQ code. This was implied by the intentionally-alarmist title of my post ("LINQ Closures May Be Hazardous to Your Health!"), but some readers missed the point. Let's take a closer look at what, exactly, is wrong with this LINQ code and how it should be properly written.

First of all, the example code exhibits several nasty smells:

  1. It isn't portable. There's no guarantee that other LINQ providers will actually support closures.
  2. It isn't maintainable. The code is an obvious maintenance headache—especially if it will be handled by more than one person.
  3. It isn't declarative. LINQ syntax is designed to be declarative, but this code mixes in imperative logic.
  4. It isn't flexible. The closure voodoo inhibits potential optimizations that might occur with future technologies like Parallel LINQ.

In addition to the negative consequences listed above, the closure exploited in the sample is completely unnecessary! Closures can sometimes be powerful, but this isn't really the place to exploit them. In fact, writing code like that betrays a lack of knowledge of LINQ's standard query operators. LINQ already provides an easy way to ensure that duplicate values are removed from a query expression: the Distinct operator.

Distinct is one of several query operators designed to perform set operations on queries (the other operators are Except, Intersect and Union). Using Distinct in place of the closure solves all of the afore-mentioned problems and, as a bonus, makes the code more concise.

static void Main()
{
  var query = (from m in typeof(String).GetMethods()
              orderby m.Name
              select m.Name).Distinct();
 
  foreach (var item in query)
    Console.WriteLine(item);
}

Not surprisingly, Visual Basic takes this a step further by adding a new "Distinct" keyword.

Sub Main()
  Dim query = From m In GetType(String).GetMethods() _
              Order By m.Name _
              Select m.Name _
              Distinct
 
  For Each item In query
    Console.WriteLine(item)
  Next
End Sub

However, this new keyword only gives me a mild case of VB Envy. I really like the fact that Distinct is syntax highlighted, but I much prefer how the parentheses better delineate the query expression in the C# version.

I hope this clears up any confusion that my other post might have caused. LINQ syntax is designed to be simply and declarative. Don't let your code get too fancy, and you'll reap the benefits of LINQ.

posted on Friday, September 28, 2007 9:47:20 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Tuesday, September 25, 2007
Jomo Fisher is a C# team member who works on LINQ to SQL. Recently, Jomo has been exploring F# by compiling bits of code and seeing what the F# compiler generates. So far, I've found this "Adventures in F#" series to be quite enjoyable, and I recommend it to any interested readers. Here is a list of the articles posted to date:
I should point out that this series is not an introduction to functional programming or F#. Instead, it is more technical in nature and asks the question, "How does the compiler do that?"
posted on Tuesday, September 25, 2007 7:54:10 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
UPDATE (Sep. 28, 2007): This article is really academic in nature on the topic of closures and how they fit into LINQ query expressions. It contains a highly-contrived example that is not representative of quality LINQ code. For more information, take a look at this post.

To me, one of the most interesting aspects of LINQ query expressions is that they produce lexical closures (for a detailed look at closures in C#, see my article on the topic). To illustrate this point, consider the following code:

static void Main()
{
  var filter = "Compare";
 
  var query = from m in typeof(String).GetMethods()
              where m.Name.Contains(filter)
              select new { m.Name, ParameterCount = m.GetParameters().Length };
 
  foreach (var item in query)
    Console.WriteLine(item);
 
  Console.WriteLine();
  Console.WriteLine("--- press any key to continue ---");
  Console.ReadKey();
}

This query retrieves all of the public methods on System.String whose names contain the text represented by the "filter" variable (in this case "Compare"). When compiled and run, the output is what you might guess:

{ Name = Compare, ParameterCount = 2 }
{ Name = Compare, ParameterCount = 3 }
{ Name = Compare, ParameterCount = 3 }
{ Name = Compare, ParameterCount = 4 }
{ Name = Compare, ParameterCount = 5 }
{ Name = Compare, ParameterCount = 6 }
{ Name = Compare, ParameterCount = 7 }
{ Name = Compare, ParameterCount = 6 }
{ Name = CompareTo, ParameterCount = 1 }
{ Name = CompareTo, ParameterCount = 1 }
{ Name = CompareOrdinal, ParameterCount = 2 }
{ Name = CompareOrdinal, ParameterCount = 5 }

--- press any key to continue ---

That behavior should be perfectly natural to any C# developer. Here's where things get a little tricky:

var filter = "Compare";

var query = from m in typeof(String).GetMethods()
            where m.Name.Contains(filter)
            select new { m.Name, ParameterCount = m.GetParameters().Length };

filter = "IndexOf";

foreach (var item in query)
  Console.WriteLine(item);

Can you guess what that code will output to the console?

Your answer to that question depends on your understanding of what closures are and how they work. A closure is produced when a variable whose scope extends beyond the current lexical block is bound to that block. That's a bit of a mouthful, isn't it? Allow me to clarify what I mean with a simple example.

delegate void Action();
 
static void Main()
{
  int x = 0;
 
  Action a = delegate { Console.WriteLine(x); };
 
  x = 1;
 
  a();
}

In the code above, an anonymous delegate ("a") references a variable ("x") that is declared outside of the anonymous delegate's body. This implies a lexical closure, and the variable "x" is bound to the method body of "a." The important point is that "a" is bound to the variable "x" and not its value. In other words, the value that "a" writes to the console depends upon the value of "x" at the time of its execution. Because 1 is assigned to "x" immediately before "a" is executed, 1 is output to the console.

Precisely the same thing happens in our query expression. A closure is produced for the lambda expression of the "where" clause because it references the "filter" variable, which is declared outside of the query expression. The closure binds to the variable "filter"—not its value. So, changing the value of "filter" after the query expression is defined will change the results returned by the query. In fact, if you run that code, you'll get this:

{ Name = IndexOf, ParameterCount = 3 }
{ Name = IndexOfAny, ParameterCount = 3 }
{ Name = LastIndexOf, ParameterCount = 3 }
{ Name = LastIndexOfAny, ParameterCount = 3 }
{ Name = IndexOf, ParameterCount = 1 }
{ Name = IndexOf, ParameterCount = 2 }
{ Name = IndexOfAny, ParameterCount = 1 }
{ Name = IndexOfAny, ParameterCount = 2 }
{ Name = IndexOf, ParameterCount = 1 }
{ Name = IndexOf, ParameterCount = 2 }
{ Name = IndexOf, ParameterCount = 3 }
{ Name = IndexOf, ParameterCount = 2 }
{ Name = IndexOf, ParameterCount = 3 }
{ Name = IndexOf, ParameterCount = 4 }
{ Name = LastIndexOf, ParameterCount = 1 }
{ Name = LastIndexOf, ParameterCount = 2 }
{ Name = LastIndexOfAny, ParameterCount = 1 }
{ Name = LastIndexOfAny, ParameterCount = 2 }
{ Name = LastIndexOf, ParameterCount = 1 }
{ Name = LastIndexOf, ParameterCount = 2 }
{ Name = LastIndexOf, ParameterCount = 3 }
{ Name = LastIndexOf, ParameterCount = 2 }
{ Name = LastIndexOf, ParameterCount = 3 }
{ Name = LastIndexOf, ParameterCount = 4 }

--- press any key to continue ---

Let's try to exploit this closure in a more practical way.

var filter = String.Empty;

var query = from m in typeof(String).GetMethods()
            where m.Name != filter
            select m.Name;

foreach (var item in query)
{
  Console.WriteLine(item);
  filter = item;
}

This slightly different query expression returns the names of all of the public methods on System.String that don't match the value of the variable "filter." By modifying "filter" in each iteration of the foreach loop, we are effectively filtering out all duplicate method names. This works as advertised, but there's one potential bug: it is assumed that all overloads of a method are grouped together. If there are overloads of, say, String.CompareTo that aren't adjacent in the source array, the filtering won't work properly. What we really need to do is sort the array using the "orderby" query operator.

var query = from m in typeof(String).GetMethods()
            where m.Name != filter
            orderby m.Name
            select m.Name;

WHOOPS! That doesn't work. When we execute that query, all of the method names are output to the console, including duplicates. Our modifications to the "filter" variable in the foreach loop are completely ignored. Why is that?

The reason is that "orderby" forces the entire query to be evaluated when the first element is requested. This behavior is unavoidable and breaks the normal delayed evaluation of a query expression. However, we can still make the closure work properly by ensuring that the sort happens before filtering.

var query = from m in typeof(String).GetMethods()
            orderby m.Name
            where m.Name != filter
            select m.Name;

Now we get the output that we want:

Clone
Compare
CompareOrdinal
CompareTo
Concat
Contains
Copy
CopyTo
EndsWith
Equals
Format
get_Chars
get_Length
GetEnumerator
GetHashCode
GetType
GetTypeCode
IndexOf
IndexOfAny
Insert
Intern
IsInterned
IsNormalized
IsNullOrEmpty
Join
LastIndexOf
LastIndexOfAny
Normalize
op_Equality
op_Inequality
PadLeft
PadRight
Remove
Replace
Split
StartsWith
Substring
ToCharArray
ToLower
ToLowerInvariant
ToString
ToUpper
ToUpperInvariant
Trim
TrimEnd
TrimStart

--- press any key to continue ---

The moral here is to be careful. Exploiting closures in query expressions can be powerful but tricky to get right.

posted on Tuesday, September 25, 2007 6:53:23 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Friday, September 21, 2007
I had the priviledge to attend Bill Wagner's "C# 3.0: Think More, Type Less" talk last night at the Greater Lansing User Group .net. As usual, Bill explained each of the new features coming in C# 3.0 with the ease of a true Jedi Master. If you have an opportunity to see this talk, I highly recommend it.

posted on Friday, September 21, 2007 9:04:24 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Thursday, September 20, 2007
This is the sixth article in my series on functional programming ideas using C#. As promised, we're digging into partial application to explore more practical applications of currying.
posted on Thursday, September 20, 2007 7:43:07 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Friday, August 17, 2007
Several weeks ago, I posted this bit of code that shows how we might use a C# 3.0 query expression to calculate the sum of the squares of an array of integers.
static void Main()
{
  var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

  var
sum = (from n in numbers
             where (n % 2) == 0
             select n * n).Sum();

  Console
.WriteLine("Sum: {0}", sum);
}

Translating this sample into Visual Basic 9.0 produces almost identical code.

Sub Main()
  Dim numbers() = New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}

  Dim
total = (From n In numbers _
               Where (n Mod 2) = 0 _
               Select n * n).Sum()

  Console.WriteLine("Sum: {0}", total)
End Sub

However, this translation is a bit naive because Visual Basic 9.0 actually provides syntax for more of the standard query operators than C# 3.0 does. While we have to call the "Sum" query operator explicitly in C#, Visual Basic allows us to use it directly in the query.

Sub Main()
  Dim numbers() = New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}

  Dim
total = Aggregate n In numbers _
              Where (n Mod 2) = 0 _
              Select n * n _
              Into Sum()

  Console.WriteLine("Sum: {0}", total)
End Sub

In fact, Visual Basic even allows us to create our own aggregate functions and use them directly in query expressions.

<Extension()> _
Function Product(ByVal source As IEnumerable(Of Integer)) As Integer
  Dim
result = 1
  For Each n In source
    result *= n
  Next
  Return
result
End Function

Sub
Main()
  Dim numbers() = New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}

  Dim total = Aggregate n In numbers _
              Where (n Mod 2) = 0 _
              Select n _
              Into Product()

  Console.WriteLine("Sum: {0}", total)
End Sub

Here we get the product of the even numbers in the array. (I removed the expression to square each even number because it produced an OverflowException.)

I should point out that there is a behavioral difference that the Visual Basic "Aggregate" keyword introduces. A standard "From" query expression is delay evaluated. That is, the results aren't actually evaluated until they are accessed through, say, a "For Each" loop. However, an "Aggregate" query expression forces the results to be evaluated immediately. In contrast, C# 3.0 query expressions always produce results that are delay evaluated.1

1A bold statement that will be completely recanted if any reader can find an example that proves otherwise.2
2Please, prove me wrong. Seriously. I'm interested in this stuff.3
3This footnote motif is clearly ripped off from Raymond Chen.

posted on Friday, August 17, 2007 7:46:31 AM (Pacific Standard Time, UTC-08:00)  #    Comments [2]

kick it on DotNetKicks.com
 Wednesday, August 15, 2007
It's time to get back to functional programming with C# 2.0. This time, I look at how the technique of "currying" fits into the picture.
posted on Wednesday, August 15, 2007 11:35:46 AM (Pacific Standard Time, UTC-08:00)  #    Comments [7]

kick it on DotNetKicks.com
 Wednesday, June 27, 2007
This time, I briefly look at how to use methods available to C# 3.0 that are equivalent to Filter, Map and Reduce.
posted on Wednesday, June 27, 2007 11:54:58 AM (Pacific Standard Time, UTC-08:00)  #    Comments [6]

kick it on DotNetKicks.com
 Thursday, June 21, 2007
After a long break, it's time to return to my informal series of articles on functional programming concepts using only C# 2.0. This time, I'm looking at the idea of higher-order functions and how to implement Map, Filter and Reduce.
posted on Thursday, June 21, 2007 8:37:03 AM (Pacific Standard Time, UTC-08:00)  #    Comments [4]

kick it on DotNetKicks.com
 Wednesday, April 18, 2007
This article delves into a certain peculiarity of the .NET garbage collector. Along the way, it explores IL, optimized JIT-compiled code and even the underlying CLR structures.
posted on Wednesday, April 18, 2007 7:08:50 AM (Pacific Standard Time, UTC-08:00)  #    Comments [6]

kick it on DotNetKicks.com
 Monday, April 02, 2007
At the moment, I'm enjoying the first-ever week-long vacation that I've taken since joining the Developer Express IDE Tools Team nearly four years ago. CodeRush and Refactor! are very exciting products to work on but I need some time to refresh and Key West is just the place to do it. (Sadly, I think my trophy wife is already upset with me because I took a moment to fix a bug this morning.)

My vacation began with some exciting news. On Sunday, just before leaving for the airport, I received an email from Microsoft honoring me with the MVP Award for C#. Frankly, I'm humbled by the award, and it's a great priveledge to be numbered among so many professionals whom I deeply respect. Thanks very much to my friends, colleagues and mentors who made this possible.

posted on Monday, April 02, 2007 8:47:56 AM (Pacific Standard Time, UTC-08:00)  #    Comments [7]

kick it on DotNetKicks.com
 Friday, March 23, 2007
One of the greatest frustration of working with delegates and events is that they can potentially cause memory leaks if they aren't unhooked. In this article, we will solve this problem in a variety of ways to get the best performance, memory use and syntax.
posted on Friday, March 23, 2007 10:12:02 AM (Pacific Standard Time, UTC-08:00)  #    Comments [14]

kick it on DotNetKicks.com
 Monday, March 19, 2007
Delegates rock. But there's a dark side to them that can cause non-obvious bugs. Read on if you dare!
posted on Monday, March 19, 2007 12:00:13 PM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Wednesday, February 28, 2007
OK, I'm done downloading the March CTP of Orcas. Everyone else can go ahead. Thanks for your patience. :-)


posted on Wednesday, February 28, 2007 4:50:29 PM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
The Orcas March CTP is out! You can get the installer version here and the VPC image here. This is first CTP that has all of the features from last May's LINQ Preview. IOW, this is a big one!

On a side note, I would appreciate everyone waiting to download until I'm finished so that I can maximize my bandwidth. TIA! ;-)

posted on Wednesday, February 28, 2007 9:18:15 AM (Pacific Standard Time, UTC-08:00)  #    Comments [2]

kick it on DotNetKicks.com
 Thursday, February 22, 2007
C# 3.0 Lambda expressions have distinct advantages over C# 2.0 anonymous methods. This article takes a look at how using lambda expressions can improve the compiler's type inference for generic methods.
posted on Thursday, February 22, 2007 6:10:30 AM (Pacific Standard Time, UTC-08:00)  #    Comments [2]

kick it on DotNetKicks.com
 Monday, February 19, 2007
At first, the syntax of C# 3.0 lambda expressions can be a bit intimidating. This article unravels the syntax to show that they are really anonymous methods on steroids.
posted on Monday, February 19, 2007 9:50:11 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Tuesday, February 13, 2007
Are you confused by all of the talk about functional programming going on in the world of C# these days? If so, maybe it's time to play a little catch up.

There are a lot of resources available that you can go to but the most valuable that I've found are the video lectures by Hal Abelson and Gerald Jay Sussman from MIT's Structure and Interpretation of Computer Programs course. These lectures were given in 1986 and may look a bit dated (I saw one guy in the class that looks like "Rusty" from "National Lampoon's Vacation") but the content is fantastic.

You can download the video lectures here.
posted on Tuesday, February 13, 2007 10:37:27 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Monday, February 12, 2007
Continuing my series on functional programming ideas, this article looks at the functional programming technique of "automatic memoization" and shows how it can be used to great effect in C# 2.0.
posted on Monday, February 12, 2007 8:28:24 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Friday, February 09, 2007
Closures are an important concept to understand as they underpin many functional programming techniques. This article peeks under the hood to see how closures are implemented in C# and discusses some ways in which they are extremely useful for producing robust code.
posted on Friday, February 09, 2007 10:47:06 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Thursday, February 08, 2007
After a bit of hiatus, I am long overdue to get some code up on this blog. To give myself some direction, this is the start of an informal series that will attempt to shed some light on the functional programming ideas that have been sneaking into the C# world. In this article, I tinker with the classic Fibonacci number sequence and how to calculate them with lightning fast, thread-safe code using closures in C# 2.0.
posted on Thursday, February 08, 2007 11:51:48 AM (Pacific Standard Time, UTC-08:00)  #    Comments [3]

kick it on DotNetKicks.com
 Saturday, November 25, 2006
posted on Saturday, November 25, 2006 7:12:43 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Monday, November 20, 2006
This article looks at the potential performance issues of String.Format() when used with StringBuilder.
posted on Monday, November 20, 2006 9:26:03 AM (Pacific Standard Time, UTC-08:00)  #    Comments [6]

kick it on DotNetKicks.com
 Tuesday, November 07, 2006
Get the details here.

posted on Tuesday, November 07, 2006 8:14:43 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Tuesday, October 24, 2006
Exploring some of the cool things you can do with extension methods in C# 3.0.
posted on Tuesday, October 24, 2006 10:13:49 AM (Pacific Standard Time, UTC-08:00)  #    Comments [6]

kick it on DotNetKicks.com
 Thursday, October 05, 2006
Today I was iterating a List<int> using a foreach loop and feeling a bit smug in knowing how much more performance-conscious I was being than if I'd tried doing the same thing with an ArrayList filled with ints. Thanks to the wonder of generics, the C# compiler neatly avoids numerous boxing operations by using a System.Collections.Generic.IEnumerator<int> instance instead of the older System.Collections.Generic.IEnumerator. Then I got to thinking: "is this really the fastest way?" Upon investigation, it turns that, no, it isn't the fastest way.
posted on Thursday, October 05, 2006 7:07:51 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com