32

So I have a custom attribute, let's call it MyCustomAttribute, which has a constructor like so:

public MyCustomAttribute(int? i)
{
   // Code goes here
}

and declares a property:

public int? DefaultProperty { get; set; }

Now if I wanted to use the property, I'd need to pass in an int or null, well that's what I'd expect.

But this gives a compiler error:

[MyCustomAttribute(1, DefaultProperty = 1)]
public int? MyProperty { get; set; }

and so does this:

[MyCustomAttribute(null,DefaultProperty = null)]
public int? MyProperty { get; set; }

The error is: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type for both the constructor and the property.

Why is this? If I change the constructor to take an int, I can pass in 0, but not null, which sort of defeats the purpose of the value (which can sometimes be null)

6
  • 1
    Where's the enum you mention in the title? (A nullable int is not an enum.)
    – dtb
    Sep 21, 2010 at 23:57
  • 3
    You could provide two constructors: one with an int parameter and one without any parameters.
    – dtb
    Sep 21, 2010 at 23:58
  • Yeah sorry, thought it was enum at first, turns out it's the nullable int
    – PostMan
    Sep 21, 2010 at 23:58
  • See edit, doesn't work for properties either, so the constructor will solve one problem, but not the other
    – PostMan
    Sep 22, 2010 at 0:01
  • @PostMan In .NET 4.6, I can make an int? property on an attribute with two constructors -- is that what you tried when you said properties don't work? I'm trying to figure out if this restriction was removed since the version of .NET you were using (.NET 4.0 I'm guessing?).
    – jrh
    Jun 14, 2018 at 19:59

6 Answers 6

31

The reason why is that while both 0 and null are constant the actual expression needed to initialize the constructor parameter is not. Both require a conversion to be a valid int? expression. Under the hood it essentially generates the following

[MyCustomAttribute(new Nullable<int>(0))]

This expression not being constant is not legal as an attribute argument

EDIT

dtb asked if this is illegal in attribute values why is it legal to have a default parameter for a nullable parameter?

void Example(int? x = null);

What you need to consider is who / what is interpreting the values.

For attributes arguments the value is interpreted by the CLR. The rules concerning legal attribute values haven't really changed since 1.0. Nullable didn't exist then hence the CLR doesn't understand nullable initialization patterns.

For default arguments the value is interpreted by the compiler at the call site of the method. The compilers understands nullable values and has a bit more room to work with as it can create non-constant expressions at the call site based on the values in IL.

How does it actually work though? First the compiler will actually encode constants and null differently in IL

// x = 0 
[DefaultParameterValue(0)]
// x = null
[DefaultParameterValue(null)]

At the call site the compiler examines these values and creates the appropriate (non-constant) expression for the parameter value.

7
  • But why can you have 'int? x = null' in a method signature?
    – dtb
    Sep 22, 2010 at 0:03
  • 1
    @dtb the reason why is that default argument values are evaluated by the compiler and attribute arguments by the CLR. The C# (and Vb.Net) compiler has special logic to make default argument values work for nullables but the CLR does not.
    – JaredPar
    Sep 22, 2010 at 0:05
  • But isn't 'int? x = 0' compiled to [DefaultParameterValue(new Nullable<int>(0))]?
    – dtb
    Sep 22, 2010 at 0:10
  • @dtb, no, a int? x = 0 parameter is actually compiled as [DefaultParameterValue(null)]
    – JaredPar
    Sep 22, 2010 at 0:12
  • @dtb, updated my answer with a full explanation of why this is possible.
    – JaredPar
    Sep 22, 2010 at 0:26
17

I know the question is why, but for the developers that are redirect to this page and are seeking for an answer. This is my workaround.

public class MyCustomAttribute: Attribute
{
    private Nullable<bool> myBoolean = null;

    public bool MyBooleanProperty { get { return this.myBoolean.GetValueOrDefault(); } set { this.myBoolean = value; } }
    public bool IsMyBooleanPropertySpecified { get { return this.myBoolean != null; } }
}
1
6

Rule of thumb for using attributes is that the type of parameters that they take can be declared with const keyword - i.e. all elementary types(int, char, etc) and string. No new keyword can be used in attribute parameters list

You cannot use an attribute like this:

[Custom(new object())]
class Class {
}

or even like this(even when DateTime is a value type):

[Custom(new DateTime(2001,1,1))]
class Class {
}

Hence using a Nullable<T> is also not allowed, because passing null or 1 is equivalent to doing this:

[Custom(new Nullable<int>())]
//[Custom(null)]
class Class {
}
[Custom(new Nullable<int>(1))]
//[Custom(1)]
class Class {
}
3

I know that this is an old question, but no-one has really answered why Nullable<> is not allowed. This conclusive answer to this lies in the documentation for compiler error CS0655:

Positional and named parameters for an attribute class are limited to the following attribute parameter types:

  • One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, or ushort.
  • The type object.
  • The type System.Type.
  • An enum type, provided that it has public accessibility, and that any types in which it is nested also have public accessibility.
  • Single-dimensional arrays of the preceding types.

This documentation page is for Visual Studio 2008, but I haven't heard of any recent changes in this area.

2
  • 2
    This does not answer why.
    – frenchone
    Jan 18, 2018 at 8:49
  • @frenchone I think it answers why the OP's code doesn't compile, but no it doesn't answer the next level of 'why', which is 'why did the compiler writers make this decision when they wrote the spec'.
    – bart
    Jan 19, 2018 at 17:43
3

I think it would be easy to forget to check IsPropertyXSet before accessing the variable. I think using a nullable is better. So here is a possible way to structure that while keeping the nullable:

public class FooAttribute : Attribute {
        public bool? SomeFlag { get; set; }

        public bool SetSomeFlag {
        get {
            throw new Exception("should not be called"); // required for property visibility
        }
        set {
            SomeFlag = value;
        }
    }
}

[Foo(SetSomeFlag=true)]
public class Person {
}

[Foo]
public class Person2 { // SetSomeFlag is not set
}

bool? b1 = ((FooAttribute)typeof(Person).GetCustomAttributes(typeof(FooAttribute), false)[0]).SomeFlag; // b1 = true
bool? b2 = ((FooAttribute)typeof(Person2).GetCustomAttributes(typeof(FooAttribute), false)[0]).SomeFlag; // b2 = null
0

A guy buys a Ferrari, but some fool set the governor (the contraption that limits the speed of the car) to 30 mph. The guy cannot change the governor to something more reasonable, so he rips it out. Now the Ferrari can go as fast as the engine can muscle.

Microsoft doesn't let you use nullables as custom attribute properties. However, Microsoft does let you use strings, which can be null, as custom attribute properties. So rip out the limitation altogether. Replace your nullable int with a string. Sure, a string is even less restrictive than a nullable int as it can have non-integer values like "bob", but that's the price you pay for Microsoft screwing up custom attributes, a language feature, for an implementation detail in the CLR that should be irrelevant.

Here's my example.

public abstract class Contract : Attribute, IContract
{
    public abstract void Check (Object root, String path, Object valueAtPath);
}

public sealed class DecimalPlacesContract : Contract
{
    public String MinimumMantissaCount
    {
        get
        {
            return minimumMantissaCount?.ToString();
        }

        set
        {
            minimumMantissaCount = value == null ? (int?) null : Int32.Parse(value);
        }
    }

    public String MaximumMantissaCount
    {
        get
        {
            return maximumMantissaCount?.ToString();
        }

        set
        {
            maximumMantissaCount = value == null ? (int?) null : Int32.Parse(value);
        }
    }

    public String MinimumSignificantDigitCount
    {
        get
        {
            return minimumSignificantDigitCount?.ToString();
        }

        set
        {
            minimumSignificantDigitCount = value == null ? (int?) null : Int32.Parse(value);
        }
    }

    public String MaximumSignificantDigitCount
    {
        get
        {
            return maximumSignificantDigitCount?.ToString();
        }

        set
        {
            maximumSignificantDigitCount = value == null ? (int?) null : Int32.Parse(value);
        }
    }

    private int? minimumMantissaCount;
    private int? maximumMantissaCount;
    private int? minimumSignificantDigitCount;
    private int? maximumSignificantDigitCount;



    public override void Check (Object root, String path, Object valueAtPath)
    {
        decimal? value = valueAtPath as decimal?;

        int mantissaCount = DecimalMisc.GetMantissaDigitCount(value ?? 0);
        int significantDigitCount = DecimalMisc.GetSignificantDigitCount(value ?? 0);

        if (value == null ||
            mantissaCount < minimumMantissaCount ||
            mantissaCount > maximumMantissaCount ||
            significantDigitCount < minimumSignificantDigitCount ||
            significantDigitCount > maximumSignificantDigitCount)
        {
            throw new ContractException(this, root, path, valueAtPath);
        }
    }
}

Here's how to use the custom attribute properties.

    private class Dollar
    {
        [DecimalPlacesContract (MinimumMantissaCount = "0", MaximumMantissaCount = "2")]
        public decimal Amount { get; set; }
    }

    private class DollarProper
    {
        [DecimalPlacesContract (MinimumSignificantDigitCount = "2", MaximumSignificantDigitCount = "2")]
        public decimal Amount { get; set; }
    }

Just add quotes around the values. Unspecified properties default to null.

Any improper value like "bob" will cause a FormatException to be thrown when you call GetCustomAttributes or GetCustomAttribute off the Type or PropertyInfo instance. Sure, it would be nice to have the compile-time check of the nullable int, but this is good enough. So rip that governor right out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.