C# Tips&Tricks
Collection of Tips&Tricks for C# (.NET 2.0)

Key modifiers for Clicked-Events

Since the ToolBarButtonClickEventArgs do not contain mouse button or key state, there is no obvious way to find out whether SHIFT was pressed while clicking.

bool shiftClicked = ((System.Windows.Forms.Control.ModifierKeys & Keys.Shift) == Keys.Shift);

This also works in the OnKeyPress-method whose argument only contains the key but without any modifiers.



Quick dump of string to a File

File.WriteAllText(outFilename, outString);



The What??-Operator

I can't remember the official name, but it's quite useful:

object obj;
SomeClass d = obj as SomeClass ?? new SomeClass();


If the as-operation defaults to NULL, a new SomeClass is instantiated.



XML-Serialisation : bare minimum

var settings = new XmlWriterSettings {IndentChars = "t", Indent = true};

using (TextWriter tw = new StreamWriter(filename))
using (var xw = XmlWriter.Create(tw, settings))
{
var xs = new XmlSerializer(typeof (MapProviderList));
xs.Serialize(xw, this);
tw.Close();
}


XML-Serialisation : omit optional int-fields

Optional (nullable) int-Fields are written as:

public int? MaxTextLaenge;

If it is null however, xml serialisation produces this:



To prevent "xsi:nil", add the following:

[XmlIgnore]
public bool MaxTextLaengeSpecified
{
get { return MaxTextLaenge != null; }
}






Do not use [DefaultValue(true)] on bool properties.The Serializer will omit any field that is true (i.e. the default), and the Deserializer will set anything to false that is not there.



Why are there no icons in my treeview?

XP seems to be confused, if the visual styles are initialised too late.

So, just move this line to the front:

static void Main(string[] args) {
  // The sooner, the better
  Application.EnableVisualStyles();
  ...