Expand an array to a given size

Some functions expect an array with a minimum size. While this is generally bad coding sometimes you can’t avoid it (e.g. with csv files). That’s when this piece of code comes in handy: (it’s an extension method, so it only works on .NET 3.5) public static class ArrayHelper { /// <summary> /// Expands an array […]

String comparison

Something not many people know: when you need to compare 2 strings in C#.NET you can use the == operator overload: if(firstString == secondString) { //… } This is case sensitive. But when you need to ignore the case please don’t use this: if(firstString.ToLower() == secondString.ToLower()) { //… } or this: if(firstString.ToLower().Equals(secondString.ToLower())) { //… } […]

Cast vs ‘as’

What’s the difference? object dinner = new Dinner(); Dinner myDinner2 = (Dinner) dinner; Dinner myDinner = dinner as Dinner; Well, the first cast (which is really a cast) throws an error if dinner is null. The second one doesn’t, so you have to check that by yourself. Also see the MSDN reference on the ‘as’ […]

WinForms: Labels and ampersands

Today I bumped into this problem at work. I had a label on a form and I had to display an employee’s department. Quite easy, but the department sometimes contains an ampersand. And that ampersand was not displayed. I went looking for this problem and I bumped into this property (in System.Windows.Forms.Label): Label.UseMnemonic Property Setting […]

WPF: FileDialogs on Vista 64-bit, use the Manifest!

Rick Brewster made this comment on my previous post about the Inconsistent FileDialogs. So I decided to fire up his solution: I’ve created an empty WPF project, with a Window called ‘Main’ with the following code: using System.Windows; using Microsoft.Win32; namespace OpenFileDialogNewStyle { /// /// Interaction logic for Main.xaml /// public partial class Main : […]

A fluent approach to C# parameter validation

Normally I don’t do this, but since this is such a great article: http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/ From the creator of Paint.NET. It’s really worth reading, if you do a lot of parameter validation. It might come in handy for your forms, or maybe even for a website. I think I’ll write something based on that really soon […]

C#: Smaller syntax for event handlers.

Using lambda functions you can shorten your event handlers. E.g.: With a normal event hander: class Test { private Timer timer; private void Timer_Elapsed(object sender, ElapsedEventArgs e) { Console.WriteLine(string.Format(“Object: {0} sends: {1}”, sender, e)); } public Test() { this.timer = new Timer(); this.timer.Elapsed += new ElapsedEventHandler(this.Timer_Elapsed); this.timer.Interval = 100; this.timer.Start(); } } With an anonymous […]