Friday, 28 January 2011

ObsoleteAttribute and the Expression Compiler

I was going to post this as a question over at SO, but as I got to the end I realised a blog would probably be better (apart from the fact that only five people will read it!).

The project I'm working uses runtime objects that are produced with configuration-driven delegates built using Expression trees.

I'm doing a big functionality merge at the moment and have reached a class that, because of another that has grown, is now obsolete. So I want to make it 'properly' obsolete (generate compiler errors), go through the static codebase and change all the references.

The problem is that the class library is used, through Expressions, by a few other apps so I can't yet get rid of the class completely - I'll perhaps look at farming that job off to somebody else.

So I thought I'd just check whether the expression compiler honours the ObsoleteAttribute when marked as an error, and it doesn't:

[TestClass]
public class UnitTest1
{
    [Obsolete("obsolete", true)]
    public class ObsoleteClass
    {

    }

    [TestMethod]
    public void TestObsoletedClassViaExpression()
    {
        Type obsoleteType = typeof(UnitTest1).GetNestedType("ObsoleteClass");

        Func<object> f =
            Expression.Lambda<Func<object>>(
                Expression.New(obsoleteType)
            ).Compile();

        var o = f();

        Assert.AreEqual(obsoleteType, o.GetType());
    }
}

In my case this is actually an advantage as it means the existing projects will carry on working with the updated codebase since the only reference to this type will be through dynamically generated code.

Of course once I finally remove the type those apps will no longer work - but I won't do that until they've all been updated. That said, it would be a lot easier to go through these apps an augment them to the replacement type if the Expression compiler *did* honour the ObsoleteAttribute - just follow the runtime errors (! - sorry I mean run the tests of course ;) ).

I understand, and have exploited, the fact that the Expression compiler is allowed to do things that aren't normal - skip visibility checks etc. I also understand that attributes such as ObsoleteAttribute require a compiler to honour them as, at the IL level, they are meaningless.

However, given Extression trees' ubiquity and growing importance, shouldn't its compiler honour (or have the option to honour) the ObsoleteAttribute? On the DLR, for example, this means that a language designer must code in reflection at every step to look for Obsolete(true) declarations if he/she wants to have this functionality in their language.

Like I say, it’s a tricky one because in this particular example it’s going to work in my favour – I’m just not sure it should.