One-bytes #1: Menu item commands, boxing vs. ToString()

Hello there!
With this post I’m starting new category: one-bytes. These posts will be compiled of two or three shorter forms abut things that don’t qualify for so to say full-size post. Name of the category refers to snack meals, so called one-bite foods: one bite => one byte. Quick to prepare, good to get your taste-buds tingling.  Enjoy!

*** #1.1 Binding a command to MenuItem in ContextMenu ***
It happend one time that I had been struggling with binding a command to a MenuItem in ContextMenu. The code was more or less like this:

It turned out that since ContextMenu is not present in WPF visual tree it was not possible to bind the command as it’s usually done. The solution was to use BindingProxy class that inherits from Freezable.

Having this class we can create its instance as a resource (in my case it was an user control) and set the Data property to {Binding}:

This will bound the Data property to whatever is set as DataContext in the user control itself. Now, through the BindingProxy instance we can access that DataContext outside the visual tree:

This solution was proposed by Thomas Levesque.
Blog post by Thomas Levesque
Question on StackOverflow

*** #1.2 String.Format() vs. boxing ***
There is a thing using String.Format() method with value types (such as integers). That thing is the fact that this method takes objects as args and if a value type given as parameter it will be boxed. Boxing is a process when a value type is converted to an object. That involves moving the value from stack to heap and replacing it on a stack with a reference to heap address where the actual value is stored. (More on boxing/unboxing can be found here: [link]).
So, what can be done to avoid that – simply pass arguments with ToString() method invoked. This will save a bit on performance – that’s the theory. So I tested it. I take an array of one million integers and another array with the same amount of doubles and pass them into String.Format() method. And the theory is confirmed – avoiding boxing by invoking ToString() method makes it faster.

To make the results reliable I arranged everything as unit tests run one after another (not parallel) and the actual tests were preceded by a test that did nothing – that is to make sure that the filling arrays in test class constructor does not distort actual test running time. So the results are that the process without boxing is faster by 3,7% for doubles and 4,9% for integers. Please, keep in mind that the test sample was one million values.
Does it mean that it’s no point in invoking ToString()? My opinion is that in this case boxing operation is redundant and not necessary so it should be avoided.

More on dictionaries


Sometime ago I mentioned usage dictionaries to workaround lack of possibility to use variable which name is stored in another variable. It is useful trick (at least for me – beginner) but dictionaries may be employed to perform multitude of tasks. So, to preserve my newly gained skills I present most important aspects of dictionaries.

The main idea behind dictionaries is to have a structure that holds certain values tied to certain keys. It may be depicted as 1-D array which instead of numeric indexes uses any type of variables as example below shows:



Dictionary is a collection. To use it you need to include appropriate namespace: System.Collections.Generic. Definition of a dictionary must specify three things: its name, type of key and type of stored value:

The example below initialises empty dictionary – it was created using a constructor that doesn’t take any arguments. However, this is not the only option. Visual Studio suggest six different variations of constructor. You can set initial size of a dictionary, method of comparing keys – I am not going to describe each constructor as Visual Studio does that sufficiently. I just mention that it is possible to initialise a dictionary using a constructor that takes existing dictionary as an argument. Such action will copy of an argument dictionary to the newly created one. I find it most useful.



Adding new element
It is that simple that I was tempted to omit that, but for sake of conscientiousness here’s a quick example. To add a new element to a dictionary you need to use Add method and provide key and value of new element:

Accessing/modifying value of an element

Again, it’s very simple. Code below illustrates that:

Looping through whole dictionary
It is no secret that to run through whole dictionary you have to use foreach loop. To correctly design that loop you need to use KeyValuePair as an iterator. It is also necessary to provide types of keys and values accordingly to dictionary we want to loop through.

Other useful methods for dictionaries
Here are some other methods that you may find useful. These are quite simple operations so their description will be presented together with the code.



So, now we have basic comprehension of what dictionaries are and how to use them. I am sure you will easily find a task that which can utilise dictionaries. But to provide an example I’ll show one possible implementation.
Currently, I am writing an application which will allow user to switch between different languages (dictionaries, languages – that obvious, isn’t it?). The plan is to store language data in an XML file and load its content to a dictionary. Then, instead of hard-coding every word that is visible for end-user the program will display data stored in the dictionary. Here’s a class that allows that:

The class is static – there’s no need to create various instances as only one language can be displayed. The class has only one property – LoadedLanguage – a dictionary that uses string key to store string values.
There are two methods: method ExistLanguge(string) checks if a language file chosen by user exists. If it does the method returns true and the program continues. If the file doesn’t exist the program displays a warning message. Additionally, if the chosen language is English and its XML file doesn’t exist the program terminates as English is default language.
Another method is used to load specified language to the dictionary. As earlier said the language data is stored in the XML file. That XML file is divided into sections depending on which form it relates to.

Method LoadLanguage(string, string) takes as arguments language to load and section of XML file to load. Then it loops through the XML file and creates key/value pairs in the dictionary according to nodes present between specified area. Then these pairs are used in various parts of the program to display labels in specified language.

So, that quick guide through dictionaries would be it for today. Enjoy!

Examples (*.cs)