Skip to content

Hardware articles

8 things you probably didn’t know about C#  

Here’s a few unusual things about C# that few C# developers seem to know about.

1. Indexers can use params

We all know the regular indexer pattern x = something[“a”] and to implement it you write:

public string this[string key] {
  get { return internalDictionary[key]; }
}

But did you know that you can use params to allow x = something[“a”, “b”, “c”, “d”] ?

Simply write your indexer like this:

public IEnumerable<string> this[params string[] keys] {
  get { return keys.Select(key => internalDictionary[key]).AsEnumerable(); }
}

The cool thing is you can have both indexers in the same class side-by-side. If somebody passes an array or multiple args they get an IEnumerable back but call with a single arg and they get a single value.

2. Strings defined multiple times in your code are folded into one instance

Many developers believe that:

if (x == "" || x == "y")

will create a couple of strings every time. It won’t.

C#, like many languages, has string interning and every string your app compiles with gets put into an in-memory list that is referenced at runtime.

You can use String.Intern to see if it’s currently in this list but bear in mind that doing String.Intern(“what”) == “what” will always return true as you just defined another string in your source. String.IsInterned(“wh” + “at”) == “what” will also return true thanks to compiler optimizations. String.IsInterned(new string(new char[] { ‘w’,’h’,’a’,’t’ }) == new string(new char[] { ‘w’,’h’,’a’,’t’ }) will only return true if you have “what” elsewhere in your program or something else at runtime has added it to the intern pool.

If you have classes that build up or retrieve regularly used strings at runtime consider using String.Intern to add them to the pool. Bear in mind once in they’re there until your app quits so use String.Intern carefully. The syntax is simply String.Intern(someClass.ToString())

Another caveat is that doing (object)”Hi” == (object)”Hi” will return true in your app thanks to interning. Try it in your debug intermediate window and it will be false as the debugger will not be interning your strings.

3. Exposing types as a less capable type doesn’t prevent use as their real type

A great example of this is when internal lists are exposed as IEnumerable properties, e.g.

private readonly List<string> internalStrings = new List<string>();
public IEnumerable<string> AllStrings { get { return internalStrings; }

You’d likely think nobody can modify internal strings. Alas, it’s all too easy:

((List<string>)x.AllStrings).Add("Hello");

Even AsEnumerable won’t help as that’s a LINQ method that does nothing :( You can use AsReadOnly which creates a wrapper over the list that throws when you try and set anything however and provides a good pattern for doing similar things with your own classes should you need to expose a subset of internal structures if unavoidable.

4. Variables in methods can be scoped with just braces

In Pascal you had to declare all the variables your function would use at the start of the function. Thankfully today the declarations can live next to their assignment and use which prevents acidentally using the variable before you intended to.

What it doesn’t do is stop you using it after you intended. Given that for/if/while/using etc. all allow a nested scope it should come as only mild surprise that you can declare variables within braces without a keyword to achieve the same result:

private void MultipleScopes() {
  { var a = 1; Console.WriteLine(a); }
  { var b = 2; Console.WriteLine(a); }
}

It’s almost useful as now the second copy-and-pasted code block doesn’t compile but a much better solution is to split your method into smaller ones using the extract method refactoring.

5. Enums can have extension methods

Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

enum Duration { Day, Week, Month };

static class DurationExtensions {
  public static DateTime From(this Duration duration, DateTime dateTime) {
    switch duration {
      case Day:   return dateTime.AddDays(1);
      case Week:  return dateTime.AddDays(7);
      case Month: return dateTime.AddMonths(1);
      default:    throw new ArgumentOutOfRangeException("duration")
    }
  }
}

I think enums are evil but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

6. Order of static variable declaration in your source code matters

Some people insist that variables are ordered alphabetically and there are tools around that can reorder for you… however there is one scenario where re-ording can break your app.

static class Program {
  private static int a = 5;
  private static int b = a;

  static void Main(string[] args) {
   Console.WriteLine(b);
  }
}

This will print the value 5. Reorder the a and b declarations and it will output 0.

7. Private instance variables of a class can be accessed by other instances

You might think the following code wouldn’t work:

class KeepSecret {
  private int someSecret;
  public bool Equals(KeepSecret other) {
    return other.someSecret == someSecret;
  }
}

It’s easy to think of private as meaning only this instance of a class can access them but the reality is it means only this class can access it… including other instances of this class. It’s actually quite useful for some comparison methods.

8. The C# Language specification is already on your computer

Providing you have Visual Studio installed you can find it in your Visual Studio folder in your Program Files folder (x86 if on a 64-bit machine) within the VC#\Specifications folder. VS 2010 comes with the C# 5.0 document in Word format.

It’s full of many more interesting facts such as:

  • i = 1 is atomic (thread-safe) for an int but not long
  • You can & and | nullable booleans with SQL compatibility
  • [Conditional(“DEBUG”)] is more useful than #if DEBUG

And to those of you that say “I knew all/most of these!” I say “Where are you when I’m recruiting!” Seriously, it’s hard enough trying to find C# devs with a solid understanding of the well-know parts of the language.

[)amien

Using your Xbox Kinect as a webcam for Skype on Windows  

Thanks should go to ScottOrange on the MSDN forums however it’s along thread that has lots of pieces to pick out and try.

Still getting odd noise, corruption and other issues in Skype. Wouldn’t recommend using a Kinect as a webcam on Windows right now.

What worked for me (eventually):

  1. Download the Kinect SDK from Microsoft
  2. Install the Visual Studio 2010 Runtime if you don’t already have it
  3. Go to the KinectCPP site and download KINECTSQM.DLL and MSRKINECTNUI.DLL
  4. Create a folder for your Kinect camera drivers to live and copy those two files there
  5. Go to Wildbill’s Github repo and download the three files there into the same folder
  6. Open a Command Prompt as Administrator and CD into the folder
  7. Type install and press return

You should get a success message. If you don’t then you probably missed steps 2 or 3 – if all else fails open KinectCam.ax in Dependency Walker and see which DLL it claims it can’t find. (the IESHIM one missing is fine)

Restart Skype and see if it shows up in the list of cameras. If it doesn’t.

  1. Quit Skype entirely
  2. Go to %appdata%\Skype\shared_dynco in Windows Explorer
  3. Delete dc.db
  4. Restart Skype

[)amien

Build a great Windows 8 developer & gaming desktop for $900-$1500  

Prices last updated 13 June 2013

Parts for my PC buildWith Windows 8 right around the corner it’s time to build a new desktop PC that will scream for both development and gaming.

Having set a personal budget of around $1500 I started the arduous process that every DIY PC builder has gone through… researching parts and playing with specifications until it feels just right.

These are the parts I finally landed on and a second choice if my budget was lower that would deliver almost as much for a lot less.

Please note that Amazon prices go up and down all the time so keep an eye on your basket! :)

My list doesn’t include a keyboard, mouse or monitor as I already have ones I love. You probably do too.

Processor

Intel Core i7-3770K 3.5GHz Quad-Core $320

I went with Intel’s fastest i7 non-Extreme desktop chip that allows over-clocking in case I felt like going that way (I haven’t yet).

If running virtual machines are an important part of your life – and for many developers that’s true – then check out the Intel Core i7-3770S which has Intel Virtualization for Directed IO (vt-D) but gives up the over-clocking and runs at a more modest 3.1GHz.

Cheaper: Intel Core i5-3570K Quad Core comes in at $110 less and provides very similar performance for games as the main difference is the reduced cache and lack of hyper-threading. If you’re not running heavily-multithreaded applications you’re unlikely to notice much difference in performance.

Mainboard

MSI Z77A-GD65 $176

This “military-grade” Intel Z77 chipset based motherboard from MSI works great with the 3770K chip and provides 4 USB 3.0 sockets and 4 SATA 6Gbps ports instead of the usual 2 giving up PCI slots entirely for 3 PCIe instead. It can support three graphics cards in either SLI or CrossFire in x8/x4/x4 configurations and has Intel networking.

Cooling has been carefully thought out and includes head-pipes and a low-profile heat-sink. With a two-digit debug display, dual BIOS, UEFI support and one-button over-clocking it’s hard to mess this up.

BIOS flash update was painless.I didn’t have much luck with MSI’s Live Update as it doesn’t actually install things so just head to the driver download page and pick the drivers you’ll be using. In my case I skipped a number of the Intel ones such as the graphics, etc. You might be tempted to head to Intel’s site instead but I found newer versions were actually available from MSI instead.

Cheaper: Gigabyte GA-Z77-DS3H $110 has good reviews and includes the dual UEFI BIOS too but looses the x8/x4/x4 mode for 3 graphics cards, Atheros networking and is not as over-clocking friendly.

RAM

Corsair Vengeance LP 16GB (2 x 8GB) DDR3-1600 $116

Corsair are a well known brand with a solid reputation. This RAM is fast at 10-10-10-27 timings, low-profile (don’t get in the way of large CPU coolers) and is provided as two 8GB modules not four 4GB which leaves you room to upgrade nicely in the future.

That is the RAM I meant to buy – alas I picked up the older XMS3 which is slower (11-11-11-30 at 1600MHz) and not recommended.

Cheaper: Corsair 8GB for $70 offering the same performance at half the capacity should be good enough for most games and development projects.

Storage

Samsung 840 Pro 256GB 2.5″ SSD $219

I’ve been maintaining my MacBook SSD article over the last few years and originally picked the Crucial C300 series that was superseded by the M4 and now I think the sweet spot in price, performance and reliability was the Samsung 830. That has since been replaced by the 840 Pro. Link & price updated!

Cheaper: At $98 the 120GB model of the Samsung 840 (non-pro) is hard to pass up.

If you need a lot more storage pair it with a 2.5TB Western Digital Caviar Green for $129 more to hold files that aren’t performance critical like video, music, photos etc.

Video card

EVGA GeForce GTX 680 2GB OC2 $420

Nvidia and ATI still battle it our going back and forth as leaders in a market that seems rather stale.  I couldn’t resist aiming high-end card (the GTX 690 is just insane in both perf and price) and so settled on the GTX 680.

With most manufacturers basing their cards on the reference designs the only real choice is the bundle and RAM and clock speed tweaks. The EVGA comes in at a good price and the over-clocked version nudges up the perf for no extra cost.

Cheaper: The cheapest option would be to use the Intel HD 4000 graphics built into the CPU but gaming performance will suffer. I’d go for the EVGA GTX 660Ti 2GB at $295 instead.

Case

Antec One Hundred ATX Mid Tower $65

I had a hard time choosing a case. My last PC was in the deliciously simple black Lian-Li PC60 all-aluminum and today’s market felt limited once you discount the spiky, alien or nightclub themed offerings.

The Antec One Hundred has a lot of positive reviews and has a nice black mesh look and painted interior for a very low price. The power supply lives in the bottom to provide better cooling and a lower center of balance. Cooling is via two two-speed fans at the rear either side of the CPU – a 120mm on the back and a 140mm at the top with air coming through the front of the case which appears as 9 mesh sections although only the top 3 are actually removable 5.25″ bays and the fourth segment holding a removable 3.5″ one.

Cheaper: For $35 you can grab the NZXT Technologies Source 210 which still has a nice interior and look. Or you coul all the pieces in a pile separated with pieces of cardboard.

Power supply

Corsair AX750W ATX12V / EPS12V $150

I’ve had a fair amount of bad experience with poor power supplies. Some have blown out, rattled, tripped or turned out to be responsible for instabilities.

This time I decided to pay off the power gremlins with a very high quality, quiet, efficient and powerful-but-not-crazy power supply and I also wanted modular.

The cables came in a smart little sturdy bag and so assembly was a case of finding the right cable then routing it down to the power supply and finding the right offset in one of the two long banks of almost identical looking connectors. This was a little tricky but the connectors won’t let you put them in the wrong place.

Cheaper: Corsair’s CX600W $67 is half the price but gives up the modularity, some power and efficiency and quite likely produces more noise.

Build notes & noise

Front of my new PCMy machine is now fully assembled and running Windows 8 RTM and Visual Studio 2012 and Steam connected to my existing favorite Dell 2408WFP display, IBM Model M Keyboard and Logitech G500 mouse.

Self builds are never completely smooth and I was under the impression the 3770K did not come with a fan. It does but at that point I already purchased and unwrapped a CoolerMaster HyperN 520 seduced by the promise of a quiet 19dBA.

Noise is an important issue for me and running six fans (120mm back case, 140mm top case, 2x80mm cpu, power supply, graphics) was never going to be an acceptable option.Thankfully the power-supply fan is rarely even on and the 680 fan is very quiet.

The first step was to remove the CPU fans as they were the loudest and surprisingly the CPU did not get too hot – quite likely due to the sheer size of the heat-sink of the 520. Experimenting with the case fans revealed that the just the 120mm fan on low provided the least noise and still kept things reasonably quiet and plenty cool enough.

I wasn’t done yet while I could still hear it so tried a couple of replacement fans before settling on a Cooler Master Excalibur 120mm. This fan can be speed-controlled by the motherboard as it supports the 4-pin PWM system and given it’s close proximity to the CPU head-sink I plugged it into the CPU fan socket and configured the BIOS to control it to keep the CPU under 70 degrees C.

It runs whisper-quiet at 800 RPM when under normal workloads.

A peek inside... I call her Alice.

I couldn’t help but try the magic one-press over-clock button on the motherboard and watch the machine hit 4.2GHz which ran just fine for hours. If anything is holding that back it’s the fact I ordered slower Corsair memory by mistake :(

Still to come

Now that cooling is done (see above) my main areas of focus are:

  1. Try getting Intel 4000HD graphics switching via Virtu working on Windows 8 so that power usage drops under light loads
  2. Keeping an eye on disk space to see whether I should get a large mechanical drive or a second 256GB SSD… or perhaps a third in RAID-5.

In case you want to see the whole thing on Amazon I created a Listmania list Great Windows 8 gaming & developer PC self-build.

Performance

As promised here are some performance figures for my machine (with slower Corsair than above but 32GB of it) using Nvidia’s 306.23 WHQL drivers on Windows 8 64-bit RTM.

Component Details Subscore Base score
Processor Intel(R) Core(TM) i7-3770K CPU @ 3.50GHz 8.2
8.1
Determined by lowest subscore
Memory (RAM) 32.0 GB 8.2
Graphics NVIDIA GeForce GTX 680 8.1
Gaming graphics 4095 MB Total available graphics memory 8.1
Primary hard disk 72GB Free (238GB Total) 8.1

[)amien

PS I can’t believe it’s been 7 years since I last built a PC!

My one-year check-in with my Windows Phone 7  

It’s been almost a year since I bit the Windows Phone 7 bullet and put my iPhone 3G away. As a long-time Mac fan (our house is nothing but Macs) I wasn’t sure I’d last…

Contact & calendar management

Contact and calendar management is truly awesome as I wrote about previously. With the latest mango release Twitter and LinkedIn get brought into this unified system and messages that start with a text message can switch in and out of Facebook and Live Messenger as available.

What has this meant? Over the last year I’ve barely had to maintain contacts. Whenever I need to get hold of someone the information is there. If I want to see what they’re doing, it’s there. You can pin people to your start menu so having it automatically pick up a photo from a service is another bonus.

My Windows Phone is better for this than any other system I’ve used including my desktops.

Gorgeous user interface

The metro user interface is beautiful to use. It’s clear, fluid and fast and makes using the phone a breeze. You can see why Microsoft are adopting a similar user interface for their upcoming Xbox dashboard and seeing how far they can push the concept in Windows 8.

Such a bright fast user interface works best on the AMOLED displays such as that on the Focus – the LCD refresh rates on the HD7 for example seem to struggle with scrolling resulting in a shimmering on the screen.

Tasty Mango

  • Maps now includes both turn-by-turn directions (although you have to tap the screen after each one) and a useful Scout function that shows you nearby places to eat and visit.
  • Multitasking is a breeze, just double-tap the back button and visually pick the image showing the app you want to switch to. Not all apps support this yet but it’s getting better.
  • Voice has been underplayed – it’s like a mini Siri that can do a few things by voice activation such as calling people, finding places with Bing, opening applications and sending text messages. Just hold the Windows key to activate and speak :)
  • Power saver is a life-saver and something that Apple should be copying given recent iOS battery issues. It turns off wireless, email checking etc. either when you know battery is going or automatically when low and gets you through the tough spots.
  • Background music means not only can you play music in background with the built-in Zune stuff but even third party apps like Spotify can too! The controls and track names will appear on the lock screen and slide in anywhere you adjust the volume.

Hardware choice

I currently own a Samsung Focus on AT&T and regularly get to use both a HTC HD7 on T-Mobile and a HTC 7 Trophy on Verizon for testing.

Having a choice of hardware is great – you can pick the screen size (from 3.5″ to 4.7″), type, speed (1GHz to 1.5GHz) and specifications including slide-out keyboards, microSD expansion slots, a waterproof model and up to a 13.2 megapixel camera.

The negative side of having choice is that all the devices I’ve used have a combination of matt and shiny plastics none of which have the same quality feeling as the iPhone 4’s aluminum and glass. The LCD displays and the Super AMOLED with it’s PenTile display also don’t look as gorgeous as the iPhone retina display and has a sort of dithered effect with some solid colors when viewed closely.

Here’s hoping the Nokia Lumia 800 raises the bar.

Most favorite apps available

The thing that really made the iPhone were apps. The good news is the best ones are also on Windows Phone 7 too often making better use of the display through the metro style they adopt.

  • Amazon Kindle
  • Evernote
  • Facebook
  • Flixster
  • foursquare
  • IMDB
  • Netflix
  • Spotify
  • Twitter
  • YouTube

There are of course many extra great applications and games available in the marketplace and games usually count towards your Xbox LIVE gamerscore :)

Some notable omissions still exist including Pandora (can play on the site though) and Skype (only a matter of time given Microsoft’s acquisition).

Some cool extras

Hidden features

  • Calendar can skip between months and years in month mode – just tap the month for a selector
  • Calculator can turn into a scientific one when rotated left and a programmer one when rotated right

You can also check and tweak all sorts of settings via the diagnostic options.

Microsoft’s extra free apps

Microsoft put together a bunch of slick small free apps that perfectly complement the metro style look and feel. They include:

  • World Clock – Lets you setup a number of clocks around the world. Useful if you often converse with people in other time zones.
  • Tranlsator – Text translation tool that also pronounces translations between English, French, German, Italian and Spanish.
  • Weather – Simple and convenient weather application that supports multiple locations.
  • Unit Converter – Translate between various lengths, areas, volume, capacity etc.
  • Stocks – Keep track of your stocks and the indexes.
  • Shopping List – Simple shopping list management.

The niggley bits

While most of the WP7 experience is great there are some rough edges that even Mango hasn’t yet sorted out.

Overly sensitive buttons

It’s actually great having a back button and prevents wasting screen on a back button like iOS does. The problem however is that both the back and search buttons are overly sensitive. It’s difficult to hold the phone in one hand and use it without your thumb hitting the pesky back button. It’s unfortunately something even the Xbox 360 slim picked up with the eject mechanism which is suitably annoying when putting away a controller.

Microsoft should add code to limit button presses to a distinct no-touch, touch for 0.4s, no-touch process.

Volume control

For some reason the phone has only one volume control that is shared by both applications and the ring-tone so if you’re the sort of person who like your phone low and your music loud you’re going to be constantly shifting back-and-forth and in my case that results in either embarrassing rings when it should be silent and silent rings when it should be working.

The volume control needs to be context sensitive. When in an app or the background music player is active adjust the audio volume otherwise adjust ringer volume.

Equalizer settings

There’s no sound equalizer settings so if you don’t like the sound coming from your speakers or headphones you’re stuck with it.

Build in a system-wide equalizer that at least affects the background music player.

[)amien