Klaus Nji
Klaus Nji

Reputation: 18857

Attribute argument must be a constant expression

Could someone please explain to me why the following interface definition compiles with error in Visual Studio 2010?

   [IncompleteCodePort(SourceOriginType.Other, "This should be a GL abstraction depending on what OpenGL API will be used")]
    public interface IGL
    {
        /// <summary>
        /// Returns true if provided function is available or supported by graphics API
        /// </summary>
        /// <param name="funcName"></param>
        /// <returns></returns>
        bool IsFunctionAvailable(string funcName);

        /// <summary>
        /// Returns true if provided function is supported as extension by graphics API
        /// </summary>
        /// <param name="funcName"></param>
        /// <returns></returns>
        bool IsExtensionAvailable(string funcName);
    }



public class IncompleteCodePortAttribute : Attribute
    {
        public SourceOriginType SourceOriginType { get; private set; }
        public string SourceUrl { get; private set; }
        public string Reason { get; private set; }


        public IncompleteCodePortAttribute(SourceOriginType originType, string reason, string sourceUrl = null)
        {
            SourceOriginType = originType;
            SourceUrl = sourceUrl;
            Reason = reason;
        }
    }

    public enum SourceOriginType
    {
        CodePlex,
        WorldWindJdk,
        StackOverflow,
        Other
    }

and error I am getting is:

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

If I remove the custom attribute, I get no compile errors.

Upvotes: 3

Views: 7990

Answers (1)

svick
svick

Reputation: 244837

This seems to be a bug in the C# compiler in VS2010 (the code compiles fine under VS2012). It looks like the compiler doesn't treat the null in the default value of the parameter as constant.

This code doesn't compile:

[IncompleteCodePort()]
interface IGL
{}

class IncompleteCodePortAttribute : Attribute
{
    public IncompleteCodePortAttribute(string sourceUrl = null)
    {}
}

with the mentioned error message (“An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type”), but confusingly without a source code location.

Some examples of declaration of the attribute that do work:

class IncompleteCodePortAttribute : Attribute
{
    public IncompleteCodePortAttribute(string sourceUrl = "")
    {}
}
class IncompleteCodePortAttribute : Attribute
{
    private const string Null = null;

    public IncompleteCodePortAttribute(string sourceUrl = Null)
    {}
}
class IncompleteCodePortAttribute : Attribute
{
    public IncompleteCodePortAttribute()
        : this(null)
    {}

    public IncompleteCodePortAttribute(string sourceUrl)
    {}
}

Upvotes: 2

Related Questions