ConditionalAttribute Quirks

I recently saw a usage of the ConditionalAttribute that seemed a little flawed.

Note: For a quick write up of the ConditionAttribute have a look here http://tirania.org/blog/archive/2010/Jun-12.html

The usage of the attribute was as follows

public class BaseViewModel :INotifyPropertyChanged
{
    [Conditional("DEBUG")]
    public void VerifyPropertyName(string propertyName)
    {
        var myType = GetType();
        if (myType.GetProperty(propertyName) == null)
        {
            throw new ArgumentException("Property not found", propertyName);
        }
    }

    protected virtual void RaisePropertyChanged(string propertyName)
    {
        VerifyPropertyName(propertyName);

        var handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

The idea of this is to only have the overhead of reflection at development (DEBUG) time. In the production system (RELEASE) this code will be compiled out.

Now while this is fine if you have it as part of your solution it falls down when it is in a 3rd party library i.e. an assembly designed to be used as a file reference. The reason is that the ConditionalAttribute only applies at first compile. So there are two issues here

  1. 3rd party library compiles and deploys in DEBUG mode. The method VerifyPropertyName will be compile in. Now no matter what the consuming assembly does (DEBUG or RELEASE) it cannot avoid calling VerifyPropertyName. See the AlwaysDebug solution in the below source location.
  2. 3rd party library compiles and deploys in RELEASE mode. The method VerifyPropertyName will be excluded. Now no matter what the consuming assembly does (DEBUG or RELEASE) it will never call VerifyPropertyName. See the AlwaysRelease solution in the below source location.

I have included the source code here http://code.google.com/p/simonsexperiments/source/browse/ConditionalAttributeQuirks

Posted by: Simon Cropp
Last revised: 24 Dec, 2011 05:26 AM History

Comments

No comments yet. Be the first!

No new comments are allowed on this post.