Author Archives: Dave Fancher

Revisiting the Using Function

A little over a year ago I wrote about replicating F#’s using function for use in C#. Since I wrote that piece I’ve reconsidered the approach a bit. At the time, my team wasn’t using static code analysis (I know, shame on us) so I didn’t consider that passing the IDisposable instance to the function directly can sometimes cause the static analysis to raise warning CA2000.

To recap the previous post on this subject, here’s the original version of the method:

public static TResult Using<TResource, TResult>(TResource resource, Func<TResource, TResult> action)
    where TResource : IDisposable
{
    using (resource) return action(resource);
}

With this approach, Using requires you to supply an IDisposable instance. When using a factory method such as Image.FromFile as shown next, the warning isn’t raised:

var dimensions =
    IDisposableHelper.Using(
        Image.FromFile(@"C:\Windows\Web\Screen\img100.png"),
        img => new Size(img.Width, img.Height));

Quite often, though, we create instances directly via the new operator. Consider reading the contents of a file with a StreamReader, like this:

var contents =
    IDisposableHelper.Using(
        new StreamReader(@"C:\dummy.txt"),
        reader => reader.ReadToEnd());

Creating an IDisposable instance with the new operator results in the CA2000 warning. We know that we’re disposing the StreamReader but it still fails the static analysis checks. We could suppress the warning but we can easily avoid it altogether by redefining the Using method as follows:

public static TResult Using<TResource, TResult>(Func<TResource> resourceFactory, Func<TResource, TResult> action)
    where TResource : IDisposable
{
    using (var resource = resourceFactory()) return action(resource);
}

Now, instead of accepting an IDisposable instance directly, Using accepts a factory function that returns the IDisposable instance. Then, inside the Using method, we invoke the factory function and assign the result to resource. All that remains is to update the offending code to reflect the signature change:

var contents =
    IDisposableHelper.Using(
        () => new StreamReader(@"C:\dummy.txt"),
        reader => reader.ReadToEnd());

This revised approach gives us another benefit – it defers creating the IDisposable instance until Using is executing and keeps it scoped to the actual using block within the method.

Welcome, Kevin Miller!

My good friend and technical reviewer for The Book of F#, Kevin Miller, has recently started blogging over at structuredsight.com! Much of his day-to-day work involves managing build, deployment, and migration processes, so he’s primarily writing about some of the challenges he’s faced with migrating multiple SQL Server instances and query optimizations, but he also has some fun articles comparing programming languages, too.

Please take a moment and welcome Kevin to the party. I know he’d love to hear from you.

More VS2013 Scroll Bar Magic

Yesterday I wrote about map mode, an exciting enhancement to Visual Studio 2013′s vertical scroll bar. If you haven’t enabled the feature yet, go do it, I’ll wait.

If you had the Productivity Power Tools extension installed prior to enabling the feature, you may have noticed that there are some extra annotations in the scroll bar. These annotations, shown in the form of vertical lines and “bubbles” illustrate scope and nesting level.

You can control whether these annotations are displayed by changing the “Show code structure in the margin” setting under Productivity Power Tools/Other extensions in the options dialog. So far, I think they’re pretty helpful so I plan on leaving them enabled; at least for a while.

EnableCodeStructure

VS2013 Scroll Bar Map Mode

At Nebraska Code Camp this past weekend, Mike Douglas talked a bit about the developer productivity enhancements included in VS2013. One of the features that I’d missed until his talk was the vertical scroll bar’s map mode.

Beyond the now familiar annotations for changes, errors, and cursor position, the scroll bar’s map mode shows a low-resolution depiction of the structure of the code in the current file. This can be helpful for ascertaining the context of a particular piece of code or identifying duplicated code by observing patterns in the structure, among other things.

Perhaps just as useful is that when map mode is enabled, the scroll bar can also show a tooltip containing a preview of the code at any point on the map. To see the tooltip, simply hover over a point of interest.

I’ve only just started to use this feature but I think it’ll aid immensely in code discovery.

EnableScrollbarMap

Passing Arguments by Reference in F#

This past weekend I had the good fortune of speaking about F# at GR DevDay in Grand Rapids, Michigan. As part of this particular talk, I highlight how the F# compiler deals with calls to methods with out parameters. Naturally, this prompted a question about how it handles ref parameters. I don’t use ref parameters very often (ok, ever – I seem to have an aversion to side-effects!) so I had to admit that I’d never given it much thought and couldn’t immediately recall how to do it. I’m here today with the answer to the question.

Consider a C# function with the following signature:

public void DoSomethingWithRefParam(ref int refParam)

Just as with out parameters, F# doesn’t have any direct way to pass arguments by reference. Instead, we need to use a reference cell. Coming from C#, you might think the following F# code would be adequate.

// Bad, does not work
let v = 10
x.DoSomethingWithRefParam (ref v)

This code compiles but it’s not quite right. When it executes, any changes that DoSomethingWithRefParam makes to the reference cell will not be reflected in v. Why? Remember, the ref operator creates an instance of FSharpRef<_> which is a type that carries a mutable value. It is the mutable value which is passed by reference to the method. By including the ref operator in the call to DoSomethingWithRefParam as we would in C#, we’re not passing v by reference but instead wrapping the value of v in a reference cell to which we have no reference outside of the method call. To make this code work, we need to change the definition of v as follows:

let v = ref 10
x.DoSomethingWithRefParam v

Now, v is a reference cell and any changes made to its wrapped value in DoSomethingWithRefParam will be reflected whenever we access it later in the code.

Thank You!

The Book of F# wouldn’t have been possible without contributions from many people and while the acknowledgements section is nice, several individuals deserve something a bit more public. In particular, I need to thank:

  • Bill Pollock – publisher, editor
  • Alison Law – production editor
  • Seph Kramer – editor
  • Kevin Miller – technical reviewer
  • Tomas Petricek – technical reviewer
  • Bryan Hunter – foreword
  • Brian Kline – target audience reviewer

I owe each of you an enormous debt of gratitude.

Geographic and economic factors make it impractical to hold a large release party but a few of us were able to get together around the finished product (along with dinner and a few beverages).

Kevin Miller (left), Brian Kline (right), and I celebrate the book release at Red Lion Grog House in Indianapolis’ Fountain Square.

The Book of F#, Now Available

About a week ago two boxes arrived on my doorstep. Contained within were 20 copies of the Book of F#. Within a few days, I started seeing reports of additional people receiving their copies. At this point, I think it’s safe to announce that The Book of F# is finally available in both print and electronic forms!

This slideshow requires JavaScript.

To celebrate its release, I’ll be giving away a few copies at each of the following events over the next several weeks. Be sure to check each event’s site for up-to-date logistics and registration information if you’d like to attend.

NUFW
19 March
Fort Wayne, Indiana

Indy Software Artisans
20 March
Carmel, Indiana

GR DevDay
22 March
Grand Rapids, Michigan

Nebraska Code Camp
28 March & 29 March
Lincoln, Nebraska

Indianapolis Mobile .NET Developers
Date To Be Announced
Fishers, IN

Of course, if you can’t attend any of these, don’t want to wait, or take your chances on getting a free copy, you can purchase the book from No Starch Press, Amazon, Barnes & Noble, or O’Reilly. You can even find it on Safari Books Online.

Back to Basics: Streamlining the StringBuilder

To get back in the habit of blogging I thought I’d start by trying to breathe some new life into one of the oldest pieces of the .NET Framework – the StringBuilder. A few years ago I wrote about an aspect of the StringBuilder class that’s often overlooked – it’s fluent interface. Back then I speculated that one reason the fluent interface is so rarely used is that virtually every StringBuilder example, including those on MSDN, fail to highlight it by using a more imperative style. Read the rest of this entry

The Book of F#: Early Access!

The Book of F#: Early AccessThe powers-that-be at No Starch Press decided to include The Book of F# in their Early Access program! Effective immediately, you can get PDF versions of the chapters as soon as they’re deemed print-ready.

By taking advantage of this program, you have the opportunity to provide some feedback and help craft the book into its final form. What’s more, is that by using the coupon code EARLYBIRD, you can save 30% off the final release price.

I’m really excited to see the book reach this milestone and am even more excited to see the final product in print in the coming months.

2013 in review

The WordPress.com stats helper monkeys prepared a 2013 annual report for this blog. I’m disappointed that I posted only 18 articles this year – it’s almost like I’ve been busy with another project! With The Book of F# nearly complete, I hope to get back here a bit more often in 2014.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 49,000 times in 2013. If it were a concert at Sydney Opera House, it would take about 18 sold-out performances for that many people to see it.

Click here to see the complete report.

Follow

Get every new post delivered to your Inbox.

Join 628 other followers

%d bloggers like this: