C# compiler error CS0182 when building via TeamCity

When running a build via TeamCity, I started to get the following exception:

CSC error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

The same code built fine in Visual Studio 2012, and nothing had changed on the build server so clearly something in the most recent commits was triggering a difference in behaviour between the two environments.

It turns out that there’s a compiler bug in C# 4.0 (which our TeamCity server was using) involving null default parameters for attributes (an instance of which had been introduced in a recent commit) e.g.:

public SomeAttribute(SomeType someParameter = null)

When an attribute contains a parameter in its constructor that defaults to null, the compiler incorrectly treats this as being a typeless null literal rather than a constant expression and throws the exception in question.

The proper fix for this is to upgrade the compiler on the build server. However, as that isn’t always immediately practical, as a workaround you can simply cast the null parameter to the type in question e.g.:

public SomeAttribute(SomeType someParameter = (SomeType)null)

Eric Lippert provides more information about this particular bug in this StackOverflow answer.

This entry was posted in Fixes and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Todd Davis
    Posted September 6, 2013 at 3:56 pm | Permalink

    Totally saved my bacon in < 5 minutes with this (in this case though, build box was using MS Build / TFS, but still using an older version of the compiler and therefore, failing there and not locally).

  2. Sam Miller
    Posted April 17, 2014 at 11:02 am | Permalink

    Nice Post

23 Trackbacks

Leave a Reply