Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

No More Magic Strings! Presenting: @string.of

0.00/5 (No votes)
23 Nov 2010 2  
Implementing a stringof operator using expression trees
A Technical Blog article. View entire blog here.

The Problem

How many times have you seen the following code snippets?

  1. Checking method parameters

    C#
    if (executeMethod == null)
    {
        throw new ArgumentNullException("executeMethod");
    }
  2. Implementing a property in a WPF / SL view-model

    C#
    public double Size
    {
        get { return _size; }
        set
        {
            _size = value;
            RaisePropertyChanged("Size");
        }
    }

The first time I had to wrote code like this I felt uneasy. Hardcoded strings are bad practice and should be rarely used.

Even worse, using a hardcoded string of an identifier is just a bug waiting to happen.

Consider what happens when you need to refactor your code and change the name of the Size property (second example) to something different like MaxSize. The refactoring tools will not change the hardcoded string "Size" and now your WPF application stops notifying on property change the way it should!

These bugs are very difficult to spot. No compile time error, no runtime error. Nothing. The only way to spot this bug is by testing this specific functionality.

I’ve checked a small WPF application and found 158 (!) instances of these almost-bugs.

The Solution

Are you familiar with the typeof operator? Don’t you just loved it if there was a stringof operator? Well, there isn’t! So I’ve implemented the closest thing: @string.of().

To use it simply write:

C#
string s = @string.of(() => Size);

Since the implementation uses expression trees the syntax might look strange, but as I’ve said, that’s the closest you can get without being a member of the C# development team.

Here you can find a full example that uses the @string.of operator on various inputs: local variable, parameter, property, field and function.
(CodeProject users can easily download the demo project from the attached link)

That’s it for now,
Arik Poznanski.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here