Wednesday, May 05, 2010

The last several weeks have been pretty hectic for me. First, Visual Studio 2010 and .NET Framework 4 shipped. Of course, only those living in caves and under rocks missed that bit of news. However, that event forced me to leave my own cave and make a few public appearances.

  • April 12-15 - DevConnections, Las Vegas

    One thing that I love about the Bellagio is how they go out of their way to make me comfortable by naming their convention center rooms after the Teenage Mutant Ninja Turtles. Let’s see, there’s Michelangelo… Raphael… Donatello… Huh? What do you mean the rooms were named after Renaissance painters?

  • April 26 - .NET Rocks Road Trip, Houston

    Hanging out with Carl and Richard is always a blast. In the past, I’ve been left with stories that I can’t really share in mixed company. This time they turned on the microphones and pressed “record.”

  • June 7-10 – Tech Ed 2010, New Orleans

    I’ll be there. Who else is coming?
posted on Wednesday, May 05, 2010 7:00:52 AM (Pacific Standard Time, UTC-08:00)  #    Comments [2]

kick it on DotNetKicks.com
 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
 Wednesday, March 03, 2010
Module RandomCrash

    Sub Main()
        Try
            Throw New Exception
        Catch ex As Exception When DateTime.Now.Ticks Mod 2 = 0

        End Try
    End Sub

End Module
posted on Wednesday, March 03, 2010 1:04:58 PM (Pacific Standard Time, UTC-08:00)  #    Comments [3]

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
 Thursday, June 25, 2009

The other day, I caught a quick snapshot of Bethany playing with her favorite new toy:

 

A special thanks to my friend Joseph Hill for providing her favorite monkey!

posted on Thursday, June 25, 2009 8:07:05 PM (Pacific Standard Time, UTC-08:00)  #    Comments [2]

kick it on DotNetKicks.com
 Thursday, May 14, 2009

Last October, DevExpress released a massively powerful FREE tool specifically for C# developers called CodeRush Xpress. Today, in partnership with Microsoft, DevExpress has outdone themselves with a brand new version of CodeRush Xpress containing full support for both C# and Visual Basic. This release merges CodeRush Xpress with Refactor! for Visual Basic, creating one giant über-tool with an amazing features:

  • Duplicate Line
  • Highlight All References
  • Increase or Reduce Selection
  • Smart Clipboard Operations
  • Generate from Using (TDD)
  • Quick Navigation Window
  • Quick File Navigation
  • 60+ Refactorings!

Get it while it’s hot! You can download your FREE copy of CodeRush Xpress for Visual Studio 2008 from http://devexpress.com/crx.

posted on Thursday, May 14, 2009 4:59:29 PM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Tuesday, March 17, 2009

I’m back again with another post in my Yet Another Project Euler Series. As a reminder, my approach to these problems is to try to find the most beautiful solution that I can using F#. While performance is an important, I’m looking for the most elegant solutions that I can find.

Project Euler problem ten is another dealing prime numbers.

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

As you can guess, there’s not too much to this problem. In fact, we’ll declare just one simple supporting function.

let lessThan y x = x < y

Using the above function and our existing prime number generator, our solution is short and simple.

primes
  |> Seq.take_while (lessThan 2000000L)
  |> Seq.sum

I feel a little guilty that this post is so short, but that’s the benefit of spending two whole blog posts working out a prime number generator for problem seven.

posted on Tuesday, March 17, 2009 2:13:48 AM (Pacific Standard Time, UTC-08:00)  #    Comments [5]

kick it on DotNetKicks.com
 Saturday, March 14, 2009

In Visual Basic .NET, there are several cases in which the statement completion list will present the user with a list of values rather than the standard completion set. Most often, this occurs when assigning to a variable of one of the common System.Drawing types, Color, Brush or Pen.

Value Completion List

At first glance, the screenshot above might seem as if the Visual Basic IDE has hard-coded a set of values into IntelliSense, but that’s not the case. In fact, this is caused by a seldom-used feature of XML Documentation that is supported by Visual Basic .NET, but isn’t currently supported by C#1. By cracking open the the XML Documentation file for System.Drawing.dll (located at C:\Windows\Microsoft.NET\Framework\v2.0.50727\en\System.Drawing.xml on my machine), we’ll see a curious XML tag on the System.Drawing.Color definition.

<member name="T:System.Drawing.Color">
  <
summary>Represents an ARGB (alpha, red, green, blue) color.</summary>
  <
filterpriority>1</filterpriority>
  <completionlist cref="T:System.Drawing.Color" />
</
member>

The highlighted completionlist tag above is used by Visual Basic to populate the completion list with the public shared2 fields and properties from the specified class or module. In this particular case, the XML documentation causes Visual Basic to populate the completion list with the public shared properties of System.Drawing.Color.

Don’t believe me? Just comment out the System.Drawing.Color completionlist tag above, save and restart Visual Studio to see how this influences the statement completion list.

Standard Completion List

Many of you are probably thinking, “so, is this just a nifty implementation detail, or is something I can actually use?” The answer is, yes, this something you can use today to customize Visual Basic’s statement completion. The code below demonstrates how the completionlist tag can be used.

''' <completionlist cref="CommonOperations"/>
Public Class Operation
     Private ReadOnly _execute As Func(Of Integer, Integer, Integer)

     Public Sub New(ByVal execute As Func(Of Integer, Integer, Integer))
         _execute = execute
     End Sub

     Public Function
Execute(ByVal arg1 As Integer, ByVal arg2 As Integer) As Integer
         Return
_execute(arg1, arg2)
     End Function
End Class

Public NotInheritable Class
CommonOperations
     Public Shared ReadOnly Add = New Operation(Function(x, y) x + y)
     Public Shared ReadOnly Subtract = New Operation(Function(x, y) x - y)
     Public Shared ReadOnly Multiply = New Operation(Function(x, y) x * y)
     Public Shared ReadOnly Divide = New Operation(Function(x, y) x / y)
End Class

Visual Basic will automatically pick up the completionlist tag in the code above and use it to populate the completion list like so.

Custom Value Completion List

While a bit limited, it’s pretty easy to customize the statement completion list experience for Visual Basic to make certain types of APIs more discoverable. It’s as simple as a single XML tag.

1Kevin Pilch-Bisson (C# IDE Developer Lead and swell guy) has a clever idea for supporting the completionlist tag in the C# statement completion list while staying true to the C# IntelliSense model.
2The VB "Shared" keyword = static in C#.

posted on Saturday, March 14, 2009 12:23:10 PM (Pacific Standard Time, UTC-08:00)  #    Comments [4]

kick it on DotNetKicks.com
msn cams