Using C# Keywords for Variable Names

It’s possible to use C# keywords for variable names, etc.

For example if we wanted a variable called “namespace” (which is a C# keyword) we can prefix the declaration with an @ and use this prefix whenever we refer to the variable:

var @namespace = "hello";

@namespace += " world";



Three Part Conditional Numeric Format Strings (for Positive, Negative, and Zero Numbers)

When we’re formatting numbers we can use a format string that allows us to specify a different format to be used whenever the number is positive, negative or zero.

To do this we separate the 3 parts by a semicolon.

For example the format string "(+)#.##;(-)#.##;(sorry nothing at all)" will output:

  • (+)99.99 if the value was 99.99
  • (-)23.55 if the value was -23.55
  • (sorry nothing at all) if the value was zero

You can also use a two part conditional format string where the first part will be used if the number is positive or zero; the second part will be used if the number is negative.

Check out the MSDN page for more info…


For more C# tips, feel free to check out my C# Tips and Traps Pluralsight course.

Atomically Copying One Array to Another Array

If we’re copying arrays where the types may be different, sometimes we may want to do an atomic copy; that is if any of the elements in the source array can’t be converted to the destination array type, the whole copy operation will “rollback” and the target array will remain unchanged.

The Array.ConstrainedCopy method can do this for us.

Consider the code below where an array of objects (containing a string and and an int) is copied to a target array of type string.

Using .CopyTo will result in an exception and the target array being partially affected (the target array element 0 will have already been populated with the string).

Using .ConstrainedCopy will ensure that if an exception occurs the target array will be “rolled back”, i.e. none of it’s elements will have been changed.

var things = new object[] { "Sarah", 1};

var strings = new string[2];

// this will throw an exception because of the 2nd element conversion error (int to string)
// but, the target array "strings" would have been changed (the 1st string element will have been copied)
things.CopyTo(strings, 0);

// this will throw an exception because of the 2nd element conversion error (int to string)
// BUT, the target array "strings" will NOT have been changed
Array.ConstrainedCopy(things, 0, strings, 0, 2);

The constrained copy has the following parameters (from MSDN):

public static void ConstrainedCopy(
    Array sourceArray,
    int sourceIndex,
    Array destinationArray,
    int destinationIndex,
    int length


For more C# tips, feel free to check out my C# Tips and Traps Pluralsight course.

Customising the Appearance of Debug Information in Visual Studio with the DebuggerDisplay Attribute

Sometimes the display and formatting of information in the Visual Studio debugger is less than optimal.

The DebuggerDisplay attribute allows us to customise how an object is portrayed in the debug window.

Imagine a Person object p with an AgeInYears and an Name property.

By default, in the debugger this would look like:


At the “root” level for the object we just get the type name.

If we override ToString() then we would get that output here instead.

If we want to override ToString() but have a different output at the root debug level we can apply the DebuggerDisplay attribute at the class level:

[DebuggerDisplay("This person is called {Name} and is {AgeInYears} years old")]
class PersonWithDebuggerDisplay
    [DebuggerDisplay("{AgeInYears} years old")]
    public int AgeInYears { get; set; }
    public string Name { get; set; }

In the string we supply to the DebuggerDisplay attribute we can reference properties, fields, and methods in the class by wrapping them in {}.

This produces the following in the debugger:


Note that in the sample code above, the DebuggerDisplay attribute is also added to the AgeInYears property which produces the following when the object is expanded in the debugger:


The DebuggerDisplay attribute can be applied to:

  • Classes
  • Structs
  • Delegates
  • Enums
  • Fields
  • Properties
  • Assemblies

While this is not something we’d use on every class as a matter of course, it may be helpful when we are doing a lot of debug work and we want to make life easier for ourselves. For more info on usage check out MSDN.

For more C# tips, feel free to check out my C# Tips and Traps Pluralsight course.

New Pluralsight Course: C# Tips and Traps

My latest Pluralsight course: C# Tips and Traps is now live.

It’s a collection of things to:  “Short-circuit your learning of C# with this smorgasbord of handy C# and .NET features.”

It's sometimes hard to know what you don't know

Description: Whether you're still learning C# or you already have some experience, it's sometimes hard to know what you don't know. This course is designed to short-circuit your C# learning and provides a whole host of useful information about the sometimes under-used or unknown features of both the C# language and the .Net framework. It's suitable for those who are brand new to C# as well as experienced developers looking to "round off" their C# skills and "fill in the gaps".

You can watch C# Tips and Traps Pluralsight course now, also if you have a Plus level subscription you can also get access to all the demo code exercise files used in the course and play around with the things yourself.

Getting Started with SASS for Microsoft Developers

Sass (Syntactically Awesome Style Sheets) tries to make CSS fun again.

It's a set of "extensions" on top of standard CSS that make it easier to write and maintain style sheets.

A Sass file compiles down to regular CSS so it doesn't require any special browser plug-ins.

This article is aimed at Microsoft developers but the Sass language sections apply to anyone wanting to get an overview of Sass, regardless of the web programming platform or IDE you're using.


The Complete Beginners Guide to Hello World using C# .Net and Mono on Raspberry Pi

Disclaimer: some of the software used below is pre-release, use at your own risk...

This article assumes basic knowledge of writing C# and using Visual Studio - it doesn't assume any prior knowledge of Raspberry Pi or Linux.

My Parts List

You can find a list of verified peripherals here, below are the specifics of what I'm using successfully:

  • Raspberry Pi Model B (from element14 Australia)
  • 1 metre high speed HDMI lead (from element14 Australia)
  • Microsoft Comfort Curve 3000 USB keyboard;
  • Logitech M100 USB mouse;
  • SanDisk 16GB Ultra SDHC Card, Class 10, "up to 30 MB/s 200X"
  • Nokia AC-USB phone charger (output: DC 5 volt 1 amp*)
  • Cat 5 Ethernet cable (wired to Belkin wireless bridge/extender)

* It's important to have a sufficiently powerful supply.

Preparing the Operating System

Download Soft-float Debian “wheezy” image from

Extract the .img from the zip file.

Download Win32 Disk Imager (make sure you get the correct link as there's lots of advertising and other download links on the page).


Cleaner Code in Unit Tests

One thing that can quickly become messy when writing unit tests is the creation of test objects. If the test object is a simple int, string, etc then it's not as much of a problem as when you a list or object graph you need to create.

Even using object initializers you can end up taking a lot of lines of indented code, and gets in the way of the tests.

One solution is to use a 'builder' class which will construct the object for you.

For example, rather than lots of initializer code you could write:

            _sampleData = new HistoryBuilder()
                .WithTimer(false11new DateTime(200011))
                .WithTimer(false11new DateTime(200011))
                .WithTimer(true11new DateTime(200011))

 You can multiple overloads of WithTimer (for example one which create adds a default Timer).

 Implementation of HistoryBuilder:

    public class HistoryBuilder
        private readonly History _history;
        public HistoryBuilder()
            _history = new History();
        public HistoryBuilder WithTimer()
            _history.Timers.Add(new Timer());
            return this;
        public HistoryBuilder WithTimer(bool completed, int internalInteruptions, int externalInteruptions,
                                        DateTime time)
            _history.Timers.Add(new Timer
                                        Completed = completed,
                                        InternalInteruptionsCount = internalInteruptions,
                                        ExternalInteruptionsCount = externalInteruptions,
                                        StartedTime = time
            return this;
        public History Build()
            return _history;

MVVM Light Messenger Events Firing Multiple Times

If you register for a message in the ctor of your views code-behind, eg:

Messenger.Default.Register<DialogMessage>(this, DialogMessageHandler);

Every time you reload the view, i.e by navigating to it, the callback method (in this example DialogMessageHandler) can get called multiple times from the previous times ctor ran.

To fix this all you need to do create an event handler for the PhoneApplicationPage Unloaded and unregister the message (you can unregister more specifically using one of the other overloads):


Improved GridView & ListView Row Selection in ASP.NET 4.0

Previous versions of GridView and ListView selection behaviour operating in a potentially confusing way to the user. For example, if the third row was selected and then page 2 was selected, the third row on page 2 would also be selected. ASP.NET 4 fixes this by adding the EnablePersistedSelection and DataKeyNames properties to provide what MSDN calls "Persisted Selection".

To make selection work more as expected simple set EnablePersistedSelection="True" on the GridView or ListView and set the DataKeyNames property to the unique\primary key\property of the underlying databound object\row\etc.