Errors like these drive me insane

Today I was trying to fix up a website for one of our clients. I got the site out of source control but somehow or other it wouldn’t compile. I’m not going to talk about the fact it didn’t compile out of the box – We all know that is not a good situation and the person who allows source to get into a state like that needs to be slapped repeatedly with a wet fish.

What I’m going to talk about is what the eventual error turned out to be because it is not something I’ve ever seen before and it was such a bizarre thing that I can only hope it isn’t common. But if you are afflicted by it you will be pleased to know that the solution is easy, even if the discovery of what the problem actually was wasted several hours.

If you are reading this then I suspect you will probably be suffering from this problem in which case you are probably now yelling “STOP BABBLING MAN AND TELL ME WHAT TO DO”.

First, a description of the problem:

There is an ASP.NET web site project (probably does the same thing on a web application… And let’s not get in to why this is a web site project, it’s an old project and the standard now is web applications) with a number of web forms in it.

The ASPX for the default page currently looks something like this:

<%@ Page Language="C#" AutoEventWireup="true"
      CodeFile="Default.aspx.cs" Inherits="Default" %>
<html>
<head><title></title></head>
<body>
    <form id="form1" runat="server">
        Stuff that's on my page
        <asp:Label ID="MyLabel" runat="server"></asp:Label>
    </form>
</body>
</html>

Nothing too odd about that, you might say… And you’d be right. There is nothing at all wrong with this page. However, when you go to compile your website you get this error:

Infuriation 2
The name ‘MyLabel’ does not exist in the current context

But… but… but… You can see that MyLabel exists on the ASPX page and if you type in the C# or VB source file you’ll see that intellisense finds the object perfectly well. So what is going on?

Well, it is interesting to note that Page1 and Page2 are very similar to Default. In fact, so similar that when they were created the person that did this just copied Default.aspx and Default.aspx.cs (or Default.aspx.vb if that’s your poison). What they didn’t do when they made the copies was to change the page directive at the top that has the Inherits attribute that points to Default. So, Page1 and Page2 are inheriting the behaviour in Default.

When this first happened that wasn’t a problem. Page1 and Page2 had just minor cosmetic differences, the behaviour was the same and no one noticed.

At some point later someone came along and added MyLabel to Default.aspx… This still didn’t make a difference. Everything worked as normal.

Then someone came along and realised that MyLabel needed to change on some condition and added some code into the Default.aspx.cs file that modified MyLabel. At this point all hell broke loose!

Suddenly, MyLabel can’t be found and no one can figure out why. It is there on the ASPX page, intellisense picks it up, the stupid compiler can’t see it.

The Solution

Eventually, after spending a couple of hours on the problem and batting it around some collegues and doing bit of brainstorming someone (let’s call him Craig Muirhead because he figured it out in the end and deserves the credit) comes up with the idea that perhaps other pages are inheriting the wrong class. A quick find in files on the name of the class and we found it was referenced by 4 other pages. It takes a matter of moments to fix all those files to point to their respective code behind files/classes rather than the one on our hapless page. And all of a sudden everything compiles.

Technorati Tags: ,,,,

Using PushPins with the Virtual Earth ASP.NET control

This uses the July 2008 CTP of the Windows Live tools. You can download the Windows Live Tools for Visual Studio.

In this post, we’re taking a look at using pushpins with the Virtual Earth ASP.NET control. We have a page similar to the previous post, with a map control on it called VEMap.

In the code behind we have a method for adding shapes to the map as this is a multi-step process. First we need to create an object to represent the point, then an object to represent the shape (we’ll come to other shape types later, but for the moment, we’re just dealing with pushpins), finally we add the shape to the map.

The Page_Load method adds a number of shapes to the map, these pushpins represent locations where Scottish Developers have held user group meetings. The code looks like this:

protected void Page_Load(object sender, EventArgs e)
{
    // Glasgow Caledonian University
    AddShape(55.8662120997906, -4.25060659646988);

    // Dundee University
    AddShape(56.4572643488646, -2.97848381102085);

    // Microsoft Edinburgh (George Street)
    AddShape(55.9525336325169, -3.20506207644939);

    // Microsoft Edinburgh (Waterloo Place)
    AddShape(55.9535374492407, -3.18680360913277);
}

private void AddShape(double latitude, double longitude)
{
    LatLongWithAltitude point = new LatLongWithAltitude(latitude, longitude);
    Shape shape = new Shape(ShapeType.Pushpin, point);
    VEMap.AddShape(shape);
}

From this we get a fairly standard output when the application is run:

At present, this is all visual. There isn’t any real functionality. What we’ll do is add some very basic functionality, so that when you hover over a pushpin it tells you something about it. The Shape object has a Description property into which you can put an HTML fragment. So, here is the updated code:

protected void Page_Load(object sender, EventArgs e)
{
    // Glasgow Caledonian University
    AddShape(55.8662120997906, -4.25060659646988,
        "<b>Glasgow Caledonian University</b>");

    // Dundee University
    AddShape(56.4572643488646, -2.97848381102085,
        "<b>Dundee University</b>");

    // Microsoft Edinburgh (George Street)
    AddShape(55.9525336325169, -3.20506207644939,
        "<b>Microsoft Edinburgh</b> (George Street)");

    // Microsoft Edinburgh (Waterloo Place)
    AddShape(55.9535374492407, -3.18680360913277,
        "<b>Microsoft Edinburgh</b> (Waterloo Place)");
}

private void AddShape(double latitude, double longitude, string description)
{
    LatLongWithAltitude point = new LatLongWithAltitude(latitude, longitude);
    Shape shape = new Shape(ShapeType.Pushpin, point);
    shape.Description = description;
    VEMap.AddShape(shape);
}

The result when you hover over a pushpin looks like this:

That’s all great if you want the default pushpin look. However, you might want to customise the pins so they match more what you are looking for. The Shape class has a CustomIcon property which you can set to be a graphics object. In the following example I’ve used a simple png file with a red circle and an semi-transparent yellow fill.

The code now looks like this:

private void AddShape(double latitude, double longitude, string description)
{
    LatLongWithAltitude point = new LatLongWithAltitude(latitude, longitude);
    Shape shape = new Shape(ShapeType.Pushpin, point);
    shape.Description = description;
    shape.CustomIcon = "images/target.png";
    VEMap.AddShape(shape);
}

And the result looks like this:

Finding things with Virtual Earth

This uses the July 2008 CTP of the Windows Live tools. You can download the Windows Live Tools for Visual Studio.

This is a very introductory post just to show how to find things using the Virtual Earth ASP.NET control.

First you need to add an assembly reference to the Virtual Earth control to your project:

In each page that you want to use the Virtual Earth control you must add a line that looks like this at the top of the file:

<%@ Register Assembly="Microsoft.Live.ServerControls.VE"
    Namespace="Microsoft.Live.ServerControls.VE"
    TagPrefix="ve" %>

This registers the assembly allowing you to use the control.

When you view the ASPX page you will see that you have additional tools in the toolbox that relate to Virtual Earth. The one we are going to look at in this post is the Map control.

From the tool box you can drag a map control onto your design surface. The code it generates will set up a default position and zoom level which centres on the continental United States.

By default the control is a 400x400px square and has been given a name of Map1:

<ve:Map ID="Map1" runat="server" Height="400px" Width="400px" ZoomLevel="4" />

 

To start with we are going to change the defaults to something that is closer to home (well, mine at least) and centre it on central and southern Scotland and zoom in somewhat. I also don’t like the name Map1 so I’m going to change that too:

<ve:Map ID="VEMap" runat="server" Height="600px" Width="400px" ZoomLevel="8"  Center-Latitude="55.75" Center-Longitude="-3.5" />

The first thing I should comment on is the zoom level because it doesn’t really mean anything to anyone. Personally, I’d like to say “here’s a bounding box for the area I want to see, you figure out how to do that and sort out the aspect ratio for me”. Then again, maybe that’s because when I wrote a GIS system for my final year project at university that was what I did. I didn’t constrain the user to specific and artificial zoom levels. The maths behind it isn’t difficult and a modern graphics card can do that with its proverbial eyes closed. Having said that I can understand why it was done that way. It means that none of the maps are generated on the fly, it is all based on pre-existing graphic files that are retrieved as needed. This means no strained servers trying to render maps.

The zoom level ranges from 1 to 19. 1 is zoomed out to the whole world and 19 is zoomed in to street level. In between that it seems to be mostly an matter of experimentation.

As it stands the program will display a map on the page and you can zoom in or out, pan around and change display modes and so on, just like Live Maps.

Next, we’ll add some functionality to find stuff. To that end a text box (SearchTextBox) will be added in order that we can type stuff in, and a button (SearchButton) that we can submit it. The code for the button click event is as follows:

protected void SearchButton_Click(object sender, EventArgs e)
{
    VEMap.Find(string.Empty, SearchTextBox.Text);
}

The two parameters on the Find method match the two text boxes you find on Live Maps. The first parameter is the “what” (i.e. the business name or category” and the second parameter is the “where” (i.e. The address, location or landmark). If you use Live Maps a lot you’ll probably already by used to just ignoring the first box, so I haven’t included anything to populate that parameter and will just leave it empty.

Now, when the application is run the map will update when the button is clicked. It will zoom to the location you’ve specified.

At present there is no mechanism to determine where to move the map to if there is any ambiguity. For example, type “Bolton” and you’ll be taken to Bolton, England rather than Bolton, NY. Type “Washington” and you’ll be taken to the District of Columbia rather than the state. On the other hand type WA (the standard two letter abbreviation for Washington State) and you will be taken to Washington state.

The Virtual Earth control can tell you about all the places that it thought about when it was deciding where to take you. To get that we have to handle the ServerFind event on the map control. In order to do that change the ASPX markup to read:

<ve:Map ID="VEMap" runat="server" OnServerFind="VEMap_ServerFind"  Height="600px" Width="400px" ZoomLevel="8"  Center-Latitude="55.75" Center-Longitude="-3.5" />

And then add a handler in the code behind:

protected void VEMap_ServerFind(object sender, FindEventArgs e)
{
    StringBuilder sb = new StringBuilder();

    foreach (Place place in e.Places)
    {
        sb.Append("<p><strong>");
        sb.Append(place.Name);
        sb.Append("</strong> (");
        sb.Append(place.MatchCode);
        sb.Append(")<br/>");
        sb.AppendFormat("Lat: {0}, Long: {1}", place.LatLong.Latitude, place.LatLong.Longitude);
        sb.Append("</p>");
    }
    ResultLiteral.Text = sb.ToString();
}

Note: A Literal control called ResultLiteral has also been added to the page to display the results.

The ServerFind event will be raised by the map control when it finds stuff, however, you’ll notice that the page does not include the text we’ve built up. You might be thinking at this point that the event isn’t being raised at all, but put a break point down inside the code of the event. You’ll see the breakpoint is being hit.

The problem is that the ServerEvent is being handled as part of an AJAX postback rather than a page postback. If you look at the stack trace you’ll see that the map control has its own internal UpdatePanel that you would normally need to indicate that part of the page was AJAXified, so to speak. So to ensure that the code works as we would expect it to we need to add some things to the ASPX file.

First off we need a ScriptManager:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
</asp:ScriptManager>

And secondly we need an update panel of our own in order to put the controls that will be updated when the ServerFind event is handled. So the update panel, with the controls we created earlier, looks something like this.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <p>
        Search:
        <asp:TextBox ID="SearchTextBox" runat="server" />
        <asp:Button ID="SearchButton" runat="server" Text="Search"
          onclick="SearchButton_Click" />
    </p>
    <p>
        <asp:Literal ID="ResultLiteral" runat="server" />
    </p>
    </ContentTemplate>
</asp:UpdatePanel>

If we search for Bolton again the results look like this:

As you can see there are several Boltons in the world.

The FindEventArgs contains many bits of information, but in the sample above we’ve just concentrated on the Place. This gives you details of the places that have been found, how good a match it thinks the place is and where the place actually is. Obviously, the more specific you are in the search the more accurate the results are going to be and the more chance you have of getting an exact match.

Note: At present there is not much documentation for the Virtual Earth ASP.NET control. Much of the functionality has been gleaned from reading the documentation for the “classic” Virtual Earth control which is customisable through Javascript. I also found a bug, which has been reported to Microsoft, that if you happen to be in Birds Eye view then the find functionality does not work.

Method hiding or overriding – or the difference between new and virtual

When developing applications it is very important to understand the difference between method hiding and method overriding.

By default C# methods are non-virtual. If you are a Java developer this may come as a surprise. This means that in C# if you want a method to be extensible you must explicitly declare it as virtual if you want to override it.

So, what is overriding? Wikipedia has a succinct definition. Method overriding is a language feature that allows a subclass [aka derived class] to provide a specific implementation of a method that is already provided by … its [superclass] [aka base class]. The implementation in the subclass overrides (replaces) the implementation in the superclass.

The important thing to remember about overriding is that the method that is doing the overriding is related to the method in the base class.

Method hiding, by contrast, does not have a relationship between the methods in the base class and derived class. The method in the derived class hides the method in the base class.

I wouldn’t personally recommend method hiding as a strategy for developing code. In my opinion, if you feel the need to hide the method on the base class then you are most likely doing something wrong. I haven’t come across any scenarios where method hiding couldn’t be better implemented by other means, even as simple as just naming the method on the derived class to something else.

Let’s look at some code to show you what I mean. First off we are going to use this class structure (it’s my favourite when showing off inheritance, and you may have seen variations of it already on my blog).

Partial Class Diagram

Let’s say that the Dog class has a method call Bark()

public class Dog: Mammal
{
    public void Bark()
    {
        Console.WriteLine("Woof!");
    }
}

So far, so good. We can call it like this:

static void Main(string[] args)
{
    Dog d = new Dog();
    d.Bark();
    Console.ReadLine();
}

And the output of the program is as you’d expect. “Woof!” is written to the console.

Now, Chihuahuas are nippy wee things and they tend to “yip” rather than “woof” so what we’ll do is create a Bark() method in Chihuahua class that writes out “Yip!” instead.

public class Chihuahua : Dog
{
    public void Bark()
    {
        Console.WriteLine("Yip!");
    }
}

What happens here is that the C# compiler will display a warning to indicate that it has found a situation that it can guess at the intended functionality, but it really wants to to be explicit.

warning-message

‘Animals.Chihuahua.Bark()’ hides inherited member ‘Animals.Dog.Bark()’. Use the new keyword if hiding was intended.

By inserting the new keyword between the public and the void in the method declaration we can get rid of this warning. We are being explict and telling the compiler that we know what we are doing. So, what are the implications of method hiding? Consider the following bit of code:

static void Main(string[] args)
{
    Dog d = new Chihuahua();
    d.Bark();
    Console.ReadLine();
}

Well, if you have a Dog reference that actually refers to an instance of the Chihuahua class then when you call bark it will still say “Woof!” That goes against many people’s expectations. This is because you’ve actually drawn that line in the sand and are saying that the Bark method on Chihuahua is unrelated. If you hold a reference to a Dog then you may not be expected to know about the existence of a Chihuahua so if your calling code suddenly got the functionality of the Bark method in the Chihuahua class then it might break. The CLR cannot make that decision for you. If you do know about your Dog reference actually being a Chihuahua then you must cast it before using it. However, that means you are likely to have to litter your code with conditional statements based on the actual type of the object and that defeats the power of having an object oriented language.

What you should have done is make the Bark method virtual then overriden the derived version like this:

public class Dog : Mammal
{
    public virtual void Bark()
    {
        Console.WriteLine("Woof!");
    }
}
public class Chihuahua : Dog
{
    public override void Bark()
    {
        Console.WriteLine("Yip!");
    }
}

This way when you have a Chihuahua object then the correct Bark method is called regardless of the type of the reference so long as the reference type can see a Bark method on that hierarchy

The way I see it is that there is no reason to have to draw that line in the sand and use the new keyword in the context of method hiding. If you feel the need to do that then your two realistic options are either to consider whether what you really want to do is make the base virtual and then override in the derived class, or whether you need to think of a better name for the method in the derived class. If the methods are related (like the Bark example above) then method overriding is what you need. If they are not related then make that explicit by giving the method in the derived class a different name.

Developing with SQL Server 2008, deploying on SQL Server 2005

I received the following by email today:

Hi Colin! I found your blog after googling for a bit about SQL Server. I had a question for you… As someone fairly new to .NET development, would it be easier to stick with SQL Server 2005 for now, or just install SQL Server 2008 express? I ask because I don’t yet know enough about the differences between the two to know if there will be any issues when developing small web applications with 2008, but then deploying them to a hosting provider with 2005. Hope that makes sense. 🙂

Cheers,
Sean

I don’t recommend moving to SQL Server 2008 if you will ultimately be deploying on SQL Server 2005.

If you don’t know the difference between SQL Server 2005 and 2008, yet your hosting provider only supports 2005 then you would be better off sticking to working with SQL Server 2005 on your system. The reason for this is that you don’t want to accidentally stumble into features of 2008 that are not supported on 2005.

Also, even if you were intimately aware of the differences between the two versions it is still a good rule of thumb to develop on a system that is as close to the eventual live system as you can. That way you won’t get any unexpected nasty surprises when you do deploy the application and suddenly realise that things are not quite as expected.

If you have already developed the applications then you can set the compatibility level of the database to mimic SQL Server 2005:

ALTER DATABASE [MyDatabaseName] SET COMPATIBILITY_LEVEL = 90

That way you should have a similar (although not necessarily quite the same) experience as if you were developing on a real SQL Server 2005 system. There will still be things that you cannot do. I don’t think backing up your 2008 database and restoring it on a 2005 system will work.

The try-catch-return-false-throw-catch-return-false-throw-fail anti-pattern

I recently came across a wonderful anti-pattern. Well, anti-patterns are not wonderful, but the mind just boggles at the sheer bloody lunacy of this particular anti-pattern. I’m not going to show you the original code, but I’ll show a general representation of what it did:

        private void DoStuff()
        {
            if (!C())
                throw new Exception("The widget failed to process");
        }

        private bool C()
        {
            try
            {
                B();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        private void B()
        {
            bool worked = A();
            if (!worked)                throw new Exception("The process failed");
        }

        private bool A()
        {
            try
            {
                // Do stuff that might fail.
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

Now I’ve not shown all the code in order to concentrate on the weird stuff. For context DoStuff() was called from the code behind file for an ASPX page, so when it throws an exception the user will be redirected to the error page. The original exception (caught in method A()) is thrown by code from within the .NET Framework itself. It is a valid exception as the situation should only ever occur if the server is misconfigured.

There are many things wrong with this, not least is the number of things thrown. Mostly, what got me was that the wonderful diagnostic information in exceptions is repeatedly thrown away. Nothing is logged anywhere, so no one would be able to ever tell what went wrong. This is utterly hellish from a debugging point of view. In this case it was because of a misconfigured server and took several hours to track down. Had the original exception been allowed to bubble to the top (with appropriate finally blocks in place for clean up) and the exception information logged then the error could have been tracked and fixed in a matter of minutes. Luckily this happened on a dev system. I’m sure a customer would not have been pleased if their revenue generating website was brought down for hours because of a minor, but incorrect, change in a web.config file. In fact, in a production environment the tools for tracking down the error would most unlikely not exist at all. On a dev system at least a debugger and easy access to source code is present.

So, how could this code have been better written?

        private void DoStuff()
        {
            try
            {
                C();
            }
            catch (Exception ex)
            {
                // If you can add information for diagnostic purposes
                // then create a new exception and throw it. Remember to
                // add the existing exception in as the innerException.
                throw new Exception("The widget failed to process", ex);
            }
        }

        private void C()
        {
            try
            {
                B();
            }
            // Do not catch the exception, nothing was was done with it.
            finally
            {
                // Do any cleanup.
            }
        }

        private void B()
        {
            try
            {
                A();
            }
            catch (Exception ex)
            {
                // Put this caught exception into the new exception
                // in order to keep the detail. This new exception
                // adds detail to the error.
                throw new Exception("The process failed", ex);
            }
            finally
            {
                // Do cleanup
            }
        }

        private void A()
        {
            try
            {
                // Do stuff that might fail.
            }
            finally
            {
                // Do cleanup
            }
        }

This is better, if you ignore the fact that I’m catching and throwing general Exception objects – You should always throw and catch the most specific exceptions that you can.

The main benefit here is that the original exception is allowed to bubble up. When it is possible to add value to the exception a new exception is created and it holds the original as the innerException object.

Note that “The process failed” and “The widget failed to process” are stand-ins to represent meaningful and valuable exception messages. In normal circumstances messages like that do not usually add value.

Visual Studio 2008 SP1

Visual Studio 2008 SP1 is here and can be downloaded. Details of the downloads are here, and information on what SP1 brings is here. The big items for me are the Entity Framework and the performance improvements in LINQ.

However, before you go rushing off to install SP1 there are some caveats. If you’ve been running the beta Martin Hinshelwood has some advice and has also run in to problems running the Team Foundation Server SP1 install too.

Once you’ve installed the Service Pack you might want to download the Enhancements Training Kit in order to learn what’s new.

Finally, if you have Visual Studio 2008 Standard edition or above (not including trials) you can download the IconWorkshop Lite from Axialsis.

 

Mixins in .NET (again)

A while ago I wrote about Mixins in C# 3.0, at the time I was saying that you can get some of the functionality, but not all, from some of the new language features in C#3.0. The solution is a bit of a fudge because the language doesn’t support the concept. I’ve been looking at Oxygene recently and it has some language features that go a bit further than C# does and will support greater mixin-like functionality which it calls interface delegation.

Interface delegation is again a bit of a fudge, but not quite like C#. In this case the language supports this mixin-like functionality and the fudge happens in the compiler. Let’s take the class hierarchy that I used the last time:

Class-Diagram-2

In Oxygene the Dog class looks like this:

interface

type
  Dog = public class(Mammal, IRun, ISwim)
  private
      runInterfaceDelegate : RunMixin; implements IRun;
      swimInterfaceDelegate : SwimMixin; implements ISwim;
  protected
  public
  end;

implementation

end.

From this we can see that Dog inherits from Mammal and implements IRun and ISwim. The IRun interface has one method (Run), and the ISwim interface has only one method also (Swim). Of course, there could be as many methods and properties as you like.

The C# version of the Dog class, as produced by Reflector, looks like this:

public class Dog : Mammal, IRun, ISwim
{
    // Fields
    private RunMixin runInterfaceDelegate;
    private SwimMixin swimInterfaceDelegate;

    // Methods
    void IRun.Run()
    {
        this.runInterfaceDelegate.Run();
    }

    void ISwim.Swim()
    {
        this.swimInterfaceDelegate.Swim();
    }
}

As you can see, there are two private fields holding a reference to the appropriate mixin, in each of the methods the responsibility for carrying out the action is delegated to the appropriate surrogate mixin object.

What you will also notice is that you still have to instantiate the surrogate mixin objects. Under normal circumstances that would be in the constructor. If it were a real mixin you wouldn’t have the option as the mixin would be created at the same time as the object it is used with. In fact, the mixin would be mixed in as part of the object itself. So, perhaps interface delegates gives you slightly greater power than with a real mixin as you could reuse the surrogate mixin object. Then again, would you want to? I’ve not been able to think of a scenario where I would, but perhaps it could be useful.

I’d like to see interface delegates in C# at some point in the future (sooner rather than later). In fact, I’d like to see proper mixin functionality, but I recon that will require changes to the CLR to support multiple inheritance. In the meantime, I think I’ll have to write some sort of snippet in C# to quickly generate the code that Oxygene gives me in one line. Either that or start writing in Oxygene… Now, there’s a thought!

Crazy Extension Methods Redux (with Oxygene)

Back in April I blogged about a crazy thing you can do with extension methods in C#3.0. At the time I was adamant that it was a bad idea. I still think it is a bad idea, however, my thoughts have evolved a little since then and I have, possibly a solution to my hesitance to use said crazy feature.

So, if you can’t be bothered to click the link, here is a quick recap. You can create an extension method and call it on a null reference and it will NOT throw a NullReferenceException like a real method call would. At the time I was saying it was not best practice because it breaks the semantics of the dot operator which is used for member access.

Last night, I attended an excellent talk by Barry Carr on Oxygene, an Object Pascal based language that targets the .NET Framework. Oxygene has a very interesting feature, it has a special operator for dealing with calls on a reference that might be null. If that language can do it, what’s so wrong with the functionality that Extension methods potentially give? Semantics. Notice that I said that Oxygene has “a special operator”. It doesn’t use the dot operator. The dot operator still breaks if the reference is null. It has a colon operator. In this case if the reference is null (or nil as it is called in Oxygene) then the call to the method doesn’t happen. No exception is thrown.

For example. Here is the code with the regular dot operator:

class method ConsoleApp.Main;
var
  myString: String := nil;
begin
  Console.WriteLine('The string length is {0}', myString.Length);
  Console.ReadLine();
end;

And the result is that the NullReferenceException is thrown:

NullReferenceException

Here is the code with the colon operator:

class method ConsoleApp.Main;
var
  myString: String := nil;
begin
  Console.WriteLine('The string length is {0}', myString:Length);
  Console.ReadLine();
end;

And the result is that the program works, it just didn’t call the property Length as there was nothing to call it on:

Result

At this point I really would like to show you what this looks like in Reflector to show you what is going on under the hood, however, I get a message that says “This item is obfuscated and can not be translated” and the code afterwards isn’t quite right. However, the crux of it is like this in C#:

int? length;

if (myString != null)

length = myString.Length;

Console.WriteLine(“The string length is {0}”, length);

Now, back to these extension methods. After seeing this I was thinking that perhaps my total unacceptablity of allowing a null reference to be used with an extension method was perhaps incorrect. In a normal situation with an accidental null reference exception being used the NullReferenceException wouldn’t be thrown at the point of the method call (after all, the null reference is actually being passed in as the first parameter in an extension method), but somewhere in the method itself. Normal good practice would place a guard block at the start of the method so that it would be caught immediately.

However, what if you wanted to create similar functionality to the colon operator in Oxygene and have it ignore the null reference and do nothing? Well, my advice would be to create a naming convention for your extension methods to show that null references will be ignored. That way you can get the functionality with a slight semantic fudge of the dot operator. Of course, you still have to do the work and set up guard blocks to handle the null situation yourself in the extension method.

Here’s an example:

class Program
{
    static void Main(string[] args)
    {
        string myString = null;
        Console.WriteLine("The string length is {0}", myString.NullableLength());
        Console.ReadLine();
    }
}

public static class MyExtensions
{
    public static int? NullableLength(this string target)
    {
        if (target == null)
            return null;
        return target.Length;
    }
}

Tip of the Day #8 (string performance)

Concatenating strings in .NET can be very easy. There is the overloaded + operator that makes stringA + stringB + stringC statements very easy to write. But, it isn’t very performant. The reason is that strings are immutable, and concatenating strings in this way causes lots of short-lived objects to be created and thrown away, which in turn causes the garbage collector to run frequently.

There are two better ways in .NET to concatenate strings. One is to use the string.Concat() method. The other is to use the StringBuilder class. They both perform better than adding strings together, but you still have to know when to use each.

According to this article on “Performance considerations for strings in C#string.Concat() is good up to 600 strings. But, only if you have 600 strings to concatenate in a single statement. StringBuilder is better if you have more than 600 strings to concatenate, but you can do so over multiple statements. In reality, I think the benefits of appending strings over multiple statements with StringBuilder will work out better even with much less than 600 strings because to get the performance out of string.Concat() you’ll have to perform some form of setup operation to line all those strings up – and that will take time.

So, today’s tip is don’t use the plus operator to combine strings except in quick / throw-away applications. Use string.Concat() or StringBuilder instead.