Saturday, May 17, 2008

Here's a little C# quiz for your brain bones. What will happen when the following code is executed? Explain why.

Do not compile the code, just use your gray matter.

try
{
 
try
  {
   
throw new ApplicationException();
  }
 
finally
  {
   
throw new SystemException();
  }
}
catch ( Exception ex )
{
 
Console.WriteLine( ex.GetType().Name );
}

This came up during a conversation last week. I wouldn't want to bet on everyone getting the correct answer, and purely on that basis alone this should probably not be a recommended practice. It's still a gem of a thought problem.

Saturday, May 17, 2008 5:29:09 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, April 24, 2008

image Here's a handy trick for whipping C# using declarations into shape. Visual Studio 2008 will remove unused using declarations, or sort them, or both in one shot. Here's how.

In Visual Studio 2008, open a .cs file. Right-click anywhere in the block of using declarations at the top of the file and select Organize Usings. Now you can select Remove Unused Usings, Sort Usings, or Remove and Sort which does both.

Thursday, April 24, 2008 8:16:16 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, April 11, 2008

For those attending the Microsoft MVP Summit, here's some late breaking news. Patrick Smacchia (C# MVP) has a talk on NDepend that's a new addition to the schedule. It will be 5PM, Wednesday, 16 April 2008 in the MSCC. The session highlights new features of NDepend, including integration with code coverage metrics from NCover or VSTS.

If you aren't aware of NDepend, it a freaking amazing code analysis tool. It generates seriously deep code metrics, and provides tools for analyzing and visualizing the results. In the Documentation section of the website you can find a pdf "placemat" for understanding the code metrics which I created with help from Scott Hanselman and Patrick Cauldwell.

Friday, April 11, 2008 12:16:45 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, April 10, 2008

image I will be presenting a talk at PDX WebFoot this Saturday, April 12, 2008 that covers virtually every feature introduced in C# 2.0 and 3.0.

Whirlwind Tour of C# 2.0 and 3.0
Stuart Celarier — 2:30 – 3:30 pm
 

Microsoft has been working hard on changing how we write and think about code for years. Many .NET developers today still work with C# 1.0 — or use newer versions but don't use many of the new features. C# 3.0 has been released, so let's look at what's changed. In this lightning fast session we'll cover virtually every new feature of C# added since 2003. That way you can make smart decisions about which technologies to pursue without getting lost or overwhelmed. Fasten your seatbelts, we're going for a ride!

image PDX WebFoot is part of The Code Trip. It is free and open to the public. Please register through Upcoming.

The event runs from 1:00 pm to 7:00 pm, including dinner, and is located at OGI's Wilson Clark Center, 20000 NW Walker Road, Beaverton, Oregon. Other presenters include Adam Kinney, Walt Ritscher, Eric Mork, Kelly White, and the Code Trip Crew. They will be presenting and drilling into a load insanely great Silverlight goodness from the MIX08 Conference.

I hope to see some of you there!

Thursday, April 10, 2008 2:09:08 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, April 06, 2008

The InnoTech 2008 conference is here in Portland, Oregon, April 16 – 17, 2008, at the Oregon Convention Center. There are a lot of events included in the conference or associated with it. You may be particularly interested in two of those events.

The Developers track runs on Wednesday, April 16, and Thursday, April 17, and features ten sessions. A number of my friends and colleagues are presenting:

And the other sessions look great, too. A big hand to my fellow SAO Development SIG committee member, Mark Lawler, for putting the track together.

The Open Source Summit runs on Thursday, April 17. One of the many things that I really respect about the open source community is their creativity when it comes to presentations and conferences. The Open In Oregon Lightning Talks session features seven snapshot 'lightning talks' by an outstanding panel of presenters. Nice.

InnoTech 2008 is presented by the Software Association of Oregon and EasyStreet Online Services.

Sunday, April 06, 2008 6:16:32 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Saturday, April 05, 2008

image Another stop on my whirlwind tour of C# awaits you on Microsoft's Channel 9. You can find it at Whirlwind 5: What's new in C# 3 - Automatically Implemented Properties, Type Inference, Initializer (10:56).

Since this is the first whirlwind session that explores the wonderful world of C# 3.0, I lead off with a brief timeline of .NET Framework, C#, and Visual Studio releases — platform, language, and tools. One thing is clear, Microsoft has continued to innovate on all three of these elements that affect the code we write and how we write it. And they intend for the .NET Framework to be a platform on which they will continue to innovate, so expect a significant release every year or two. Language releases are probably less frequent, and tools somewhere between the two. Embrace change.

The main value of automatically implemented properties and initializers is to simplify the syntax around some commonly occurring code.

While it looks like local type inference also is aimed at simplifying syntax, it has a higher purpose. In the next whirlwind session we'll look at anonymous types. I don't want to get ahead of the game, but with an anonymous type the developer does not give the type a name, but the type is known to the compiler. Well, since an anonymous type has no name, we have to use var to declare a variable of such a type. The same also goes for declaring a variable of a generic type that is parameterized by an anonymous type. So var can be both a convenience and a necessity. You'll want to give some thought to the effect of var on the readability of your code and decide when you want to use it. Opinions about when to use and when to eschew var cover the entire spectrum.

References

Automatically Implemented Properties, section 26.9 in Overview of C# 3.0, MSDN Library

Auto-Implemented Properties, C# Programming Guide, MSDN Library

var, C# Reference, MSDN Library

Implicitly Typed Local Variables, section 26.1 in Overview of C# 3.0, MSDN Library

Implicitly Typed Local Variables, C# Programming Guide, MSDN Library

Implicitly Typed Arrays, C# Programming Guide, MSDN Library

Object and Collection Initializers, section 26.4 in Overview of C# 3.0, MSDN Library

Object and Collection Initializers, C# Programming Guide, MSDN Library

Erratum

At 8:55, I show a collection initializer that is missing instantiation of the contained type. Here's the code with the error.

var circles = new List<Circle>
{
  { Origin =
new Point { X = 2, Y = 4 }, Radius = 2 },
  { Origin =
new Point { X = 3, Y = 6 }, Radius = 4 },
  { Origin =
new Point { X = 1, Y = 1 }, Radius = 3 }
};

The corrected initializer instantiates a new Circle for each item in the collection.

var circles = new List<Circle>
{
 
new Circle { Origin = new Point { X = 2, Y = 4 }, Radius = 2 },
 
new Circle { Origin = new Point { X = 3, Y = 6 }, Radius = 4 },
 
new Circle { Origin = new Point { X = 1, Y = 1 }, Radius = 3 }
};

I had it correct in my code (honest!) and must have copied it wrong to the slides. I guess the C# syntax checker in PowerPoint 2007 isn't as good as the one in Visual Studio 2008. (The syntax is written correctly in the next code slide at 9:57.)

As a bonus for enduring the correction, consider that the example illustrates that the syntax supports a collection of types derived from Circle.

public class TexturedCircle : Circle
{
 
public string Texture { get; set; }
}
var circles = new List<Circle>
{
 
new Circle { Origin = new Point { X = 2, Y = 4 }, Radius = 2 },
 
new TexturedCircle { Origin = new Point { X = 3, Y = 6 }, Radius = 4, Texture = "bumpy" }
};

Previous episodes

Saturday, April 05, 2008 8:46:46 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, March 26, 2008

If you've been following my whirlwind tour of C# on Channel 9, with episode 4 posted I've now covered the features that I consider to be the major ones — the ones that have the biggest impact on the way we write code. There are other features that were also introduced in C# 2.0, and it is only fair to point out what I left out.

The definitive reference for 2.0 features is the article What's New in the C# 2.0 Language and Compiler, in the Visual C# Getting Started, in the MSDN Library. The topics I opted to not cover are:

Okay, your curiosity should have gotten the better of you by now. Go look up covariance and contravariance in delegates. Then you'll be able to write better code and impress your friends with sesquipedalian verbiage.

Wednesday, March 26, 2008 4:48:58 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 

My fourth screencast on modern C# language features is posted on Microsoft's Channel 9 — Whirlwind 4: What's new is C# 2 - Accessors, Static Classes, Nullable Types (9:40). This installment wraps up the major C# 2.0 features, so next time we'll be jumping into the C# 3.0 goodness.

In addition to a few resources on today's topics, I've also provided some code showing a sample of using accessor visibility and a static class. And for the careful listener, I  have some small corrections to the screencast.

Resources

Asymmetric Accessor Accessibility, C# Programming Guide, MSDN Library

Access Modifiers, C# Programming Guide, MSDN Library

Static Classes and Static Class Members, C# Programming Guide, MSDN Library

static, C# Language Reference, MSDN Library

Nullable Types, C# Programming Guide, MSDN Library

?? Operator, C# Language Reference, MSDN Library

Nullable<T> Generic Structure, .NET Framework Class Library, MSDN Library

C# Whidbey Featurette #3: Static classes, blog post by Eric Gunnerson, C# program manager. Eric provides some justification for the static class in C# 2.0.

Get a Charge From Statics with Seven Essential Programming Tips, K. Scott Allen, MSDN Magazine, June 2005.

Nullable types in C#, blog post by Eric Gunnerson, C# program manager.

Create Elegant Code With Anonymous Methods, Iterators, And Partial Classes, Juval Löwy, MSDN Magazine, Visual Studio 2005 Guided Tour issue, 2006 (Vol. 21, No. 3)

Code sample

Here is a sample that illustrates use of accessor visibility and static classes. 

using System;
using System.Collections.Generic;

namespace CSharpWhirlwind4
{
 
public class Animal
  {
   
private string name;
   
public string Name
    {
     
get { return name; }
     
private set { name = value; }  // restrict accessor visibility
    }

   
// private constructor
    private Animal( string name ) { Name = name; }

   
// nested static class, manages Animal instances
    public static class ClassFactory
    {
     
private static Dictionary<string, Animal> animals
        =
new Dictionary<string, Animal>();

     
public static Animal Create( string name )
      {
       
if ( !animals.ContainsKey( name ) )
          animals[ name ] =
new Animal( name );
       
return animals[ name ];
      }
    }
  }

 
// ...
}

The Animal class has a Name property which is marked with public visibility. Within the Name property, the set accessor is declared with private visibility, so that only members of the Animal class can set the Name property.

The Animal constructor is also declared with private visibility, so Animal cannot be instantiated except by members of the Animal class. The constructor uses the private set accessor on the Name property.

Inside of the Animal class, there is a nested class named ClassFactory which is responsible for managing Animal instances. The developer's intention is that Animal.ClassFactory should only contain static members, and therefore never be instantiated. That is indicated by declaring the class to be static.

imageTake a look at the resulting assembly in ildasm. The ClassFactory class (.class) is marked as abstract   and sealed. As an abstract class, it cannot be instantiated. And because it is sealed, it cannot be inherited by another class. Also note that the static ClassFactory has a default class constructor (.cctor), which is in fact permitted on static classes since that is a static member.

Since ClassFactory is a nested class in the Animal class, it is a member of the Animal class, and so has access to Animal's private constructor.

In this example, the ClassFactory ensures that no more than one instance of an Animal of a given name is created, as illustrated here.

Animal w1 = Animal.ClassFactory.Create( "wombat" );
Animal w2 = Animal.ClassFactory.Create( "wombat" );
Debug.Assert( w1 == w2 );   // two references to the same object

Errata

The devil is always in the details.

At 1:31, in a bout of overly excessive exuberance, on accessor visibility I said  you can change the visibility of "one, the other, or both" accessors.  Every word of that is true... except for the "or both" part.

At the end of the section on static classes (4:17) I misspoke when I said the static class "exists only because it has private members." Pretend you really heard me say it "exists only because it has static members."

Previous episodes

Wednesday, March 26, 2008 3:12:59 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, March 23, 2008

image My whirlwind tour of C# features continues with Whirlwind 3: What's new in C# 2 - Partial types, anonymous methods on Microsoft's Channel 9.

Partial types are quick and easy: split class, struct, and interface definitions across multiple files. I don't cover them in the screencast, but in addition to partial types there are also partial methods, see the resources for details.

Anonymous methods are more involved: pass a block of code inline anywhere a delegate is expected. It's a good idea to understand this concept, since lambda expressions in C# 3.0 build on anonymous methods. You'll see that in a future whirlwind episode.

Resources

Partial Classes and Methods, C# Programming Guide, MSDN Library

partial (Type), C# Reference, MSDN Library

partial (Method), C# Reference, MSDN Library

Anonymous Methods, C# Programming Guide, MSDN Library

Delegates, C# Programming Guide, MSDN Library

delegate, C# Reference, MSDN Library

Create Elegant Code With Anonymous Methods, Iterators, And Partial Classes, Juval Löwy, MSDN Magazine, Visual Studio 2005 Guided Tour issue, 2006 (Vol. 21, No. 3)

Introduction to C# Anonymous Methods, Patrick Smacchia, TheServerSide.NET

Fun with Anonymous Methods, blog post by Brad Adams. The mischievous kind of fun.

Closures and Continuations, blog post by Don Box.

Previous episodes

Sunday, March 23, 2008 9:45:02 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, March 19, 2008

The talks from the 2008 Lang.NET Symposium (28 – 30 January 2008) have been published for your viewing pleasure. The Talks page lets you choose between viewing in the browser using Silverlight, or a viewing .wmv file. If you choose the Silverlight option, hover your mouse near the bottom of the video for playback controls.

I sing the praises of Jimmy Schementi who put them up earlier without realizing the demand for them, and incurred the wrath of his ISP for bogarting the bandwidth. Now the talks are back, and some initial link boo-boos appear to be all better now.

Ted Neward already posted his copious highlights of the symposium (day one, day two, and day three), as well as list of his favorite videos. Ted spoke at Lang.NET on Scala.

Wednesday, March 19, 2008 9:48:55 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 

Whirlwind 2: What's new in C# 2 - Iterators My next whirlwind C# tour screencast is up. Whirlwind 2: What's new in C# 2 - Iterators is now on Channel 9 for your viewing pleasure. In just nine minutes you can learn what iterators are and what problem they address. Get down. Get funky.

Resources

Iterators, C# Programming Guide, MSDN Library

yield, C# Reference, MSDN Library

Create Elegant Code With Anonymous Methods, Iterators, And Partial Classes, Juval Löwy, MSDN Magazine, Visual Studio 2005 Guided Tour issue, 2006 (Vol. 21, No. 3)

Fun with Iterators and state machines, Under The Hood - Matt Pietrek (blog). Focus on the cool compiler and runtime magic that makes iterators possible. Based on prereleased Whidbey bits, but you get the idea.

Iterators with C#2, Patrick Smacchia, TheServerSide.net.

Using C# 2.0 iterators to simplify writing asynchronous code part 1 and part 2, Michael Entin's notebook (blog). Stretch your mind: using iterators to implement the .NET asynch pattern.

Previous episodes

Whirlwind 1: What's new in C# 2 - Generics (notes)

Wednesday, March 19, 2008 5:00:00 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, March 17, 2008

Whirlwind - C# GenericsMy whirlwind screencast series about C# 2.0 and 3.0 language features premiers today on Microsoft's Channel 9. Wahoo!

This is a whirlwind tour of the major language features that have been introduced in C# since the language was first released. The idea is to cover a lot of ground quickly, so that you can get the broad perspective and know what features you want to spend more time learning about. The objective is to be a mile wide and an inch deep.

In this first episode I look at a major feature introduced in C# 2.0: Generics. Watch it on Channel 9:

Whirlwind 1: What's new in C# 2 - Generics

Thanks to my gracious host and producer, Bruce Kyle, Microsoft ISV Advisor. Catch Bruce and his team on the US ISV Developer Evangelism blog.

Resources

Here are a couple of resources for digging deeper into C# generics.

Generics, C# Programming Guide, MSDN Library.

An Introduction to C# Generics, Juval Löwy, Visual Studio 2005 Technical Articles, MSDN Library.

Anders Hejlsberg - What's so great about generics? Channel 9 video. An elevator speech by the fellow who's described himself as chief randomizer on the C# team.

DotNetRock Show #34: Juval Löwy (Again). "Carl and Mark talk to Juval about, among other things, the new version of C# (2.0). Of the new features, Juval's favorite is generics."

Generic Programming Under .NET, and CLR Generics Versus C++ Templates, Stanley B. Lippman, MSDN Magazine, April and June 2005. Pair of articles compare and contrast generics and C++ templates, respectively, by a noted C++ authority.

The Design and Implementation of Generics for the .NET Common Language Runtime, Andrew Kennedy and Don Syme, Microsoft Research, 2001. If you like digging really deep, this is the original research paper on how to introduce generics into the CLR.

If you have a great C# generics resource that I didn't mention, leave a comment about it.

Monday, March 17, 2008 1:55:35 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, March 13, 2008

Last month Mary Jo Foley wrote that Microsoft is working on a new language named D as part of Oslo. Before we leap to conclusions about what D might stand for, let us recall that the C language was so named because it was derived from B which was a stripped down version of BCPL. Such is the stuff of software engineers' so-called humor. So much for musing.

Indeed, D is a declarative modeling language. According to Mary Jo, Microsoft's Chief Modeling Officer (nice title) Don Box spoke about D at the 2008 Lang.Net Symposium at the end of January. D, says Don, is about "putting more and more of your application into data and putting less in code." That is central to Oslo, the next technology wave from Microsoft, which has as its goal "making a new class of model-driven and service-enabled applications mainstream."

A few days after Mary Jo's article, InfoWorld ran an article covering Bill Gates speaking at the 2008 Office System Developers Conference on Microsoft's declarative modeling language effort, but Bill didn't mention D by name. Okay, D may very well be a project codename, so let's not get too invested in the name. And even if it is the current name of the language, what are the chances that marketing will be able let an opportunity like that go by unspoiled?

Between these two articles, Don and Bill have some pithy, interesting things to say about declarative languages and their importance in modeling complex systems.

Thursday, March 13, 2008 9:04:41 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, March 11, 2008

Slides are now available from the talk I gave with Jason Mauer, The (Re-)emergence of Declarative Programming, at Software Association of Oregon Development SIG on February 21, 2008.

The session explored declarative programming and its history, then examined recent interest in declarative styles of programming, particularly on Microsoft platforms, and what forces are driving the resurgence of declarative programming.

Join the SAO Social Network site (if you're not already a member), and go to the DevSIG group to access the slides.

Tuesday, March 11, 2008 1:41:05 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |