Non Short Circuiting C# Conditional Operators

Most of the time when writing C# programs we use the short-circuiting conditional operators. These operators do not continue evaluation once the outcome has been determined.

Take this code:

bool b = false && CheckName(name);

b = false & CheckName(name);

Here we’re performing a logical AND with the value false and the result of the CheckName method. Because we have a false, the logical AND can never be true.

The first statement using the short-circuiting AND operator (“&&”) will not execute the CheckName method because as soon as it’s determined the outcome (the first value is false and we are AND-ing) the remaining terms are not even evaluated.

More...

SHARE:

New Pluralsight Course: C# Tips and Traps 2

My latest Pluralsight course has just been released. It’s the follow-up course to the popular first C# Tips and Traps course.

Course 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 is the follow-up course to C# Tips and Traps and is designed to further 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".

Check out the course table of contents for more details.

You can start watching with a Pluralsight free trial.

SHARE:

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";

 

More...

SHARE:

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…

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

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
)

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

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:

image

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:

image

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:

image

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.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

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.

SHARE:

Binding a Dynamically Created WPF Control’s ItemTemplate to a DataTamplate Defined in XAML

I was asked a question about this on Twitter, so thought I’d create a quick post about it.

The example below shows how to use a DataTemplate that is defined in XAML with a ListView control that is dynamically created in the code behind.

1 Create a New WPF Application

Create  WPF application project in Visual Studio.

2 Create The basic XAML

Replace the contents of the MainWindow XAML to the following:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate x:Key="DaysDataTemplate">
            <Grid Background="Cyan">
                <TextBlock Text="{Binding}"></TextBlock>
            </Grid>
        </DataTemplate>
    </Window.Resources>
    <Grid Name="RootContainer" />
</Window>

This defines a DataTemplate called DaysDataTemplate that simply binds the value and has a cyan background so we can see if it is being applied.

We also give the root container (Grid) a name RootContainer so we can reference it later in the code behind.

More...

SHARE:

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 http://www.raspberrypi.org/downloads.

Extract the .img from the zip file.

Download Win32 Disk Imager http://www.softpedia.com/get/CD-DVD-Tools/Data-CD-DVD-Burning/Win32-Disk-Imager.shtml (make sure you get the correct link as there's lots of advertising and other download links on the page).

More...

SHARE:

Introducing (probably) The World's Only Mocking Framework for Windows Phone 7 (WP7)

Introducing MoqaLate

Whilst I love developing apps for Windows Phone 7, the testing aspect is hard! I'm a TDD-er by default and it's such a pain to have to hand roll my own mock objects. 

So I created MoqaLate.

It's an alpha version but is usable now.

Not sure framework is the right term but it's something that generates mocks from your interfaces.

Add to existing project from NuGet:

PM> Install-Package MoqaLate

Read more about the project.

Download an example solution.

Read (currently very basic!) documentation.

View on NuGet.org

Awesome overview diagram :)

 

SHARE: