alex in a nutshell

September 21, 2007

Decimal in c# attributes

Filed under: — Alex Salamakha @ 2:08 AM

We’re writing a new framework for our new project and decided to use Enterprise Library Validation Block as the foundation for user input validation. It worked out really well; we’re building a library of our business-specific re-usable validators. With unit testing in place, it’s heaps better than using any validation inside the forms.

There is one question that puzzles me however – why the hell decimal isn’t allowed as a parameter in attributes at CLR level?

24.1.3 Attribute parameter types

The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:
- One of the following types: bool, byte, char, double, float, int, long, short, string.
- The type object.
- The type System.Type.
- An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility.
- Single-dimensional arrays of the above types.

I’m sure CLR guys had their reasons, but since I haven’t found any documentation about that topic I’d like to know the answer.

Using double and internally use Convert.ToDecimal isn’t n option I’d like to pursue.

2 Comments »

  1. The answer can be found in this Stack Overflow thread: http://stackoverflow.com/questions/507528/use-decimal-values-as-attribute-params-in-c

    “This is a CLR restriction. Only primitive constants or arrays of primitives can be used as attribute parameters. The reason why is that an attribute must be encoded entirely in metadata. This is different than a method body which is coded in IL. Using MetaData only severely restricts the scope of values that can be used. In the current version of the CLR, metadata values are limited to primitives, null, types and arrays of primitives (may have missed a minor one).

    Decimals while a basic type are not a primitive type and hence cannot be represented in metadata which prevents it from being an attribute parameter.”
    – JaredPar, http://stackoverflow.com/questions/507528/use-decimal-values-as-attribute-params-in-c/507533#507533

    Comment by Bruce Boughton — November 23, 2009 @ 8:15 AM

  2. Argh same trouble. DecimalRangeValidator. This is an unacceptable crock of shit.

    Comment by Chris Smith — December 4, 2009 @ 6:02 AM

RSS feed for comments on this post. TrackBack URL

Leave a comment

Copyright © 1997-2010 Alexei Salamakha. All rights reserved
email: alex@salamakha.com    Alex Salamakha on Facebook    Alex Salamakha on LinkedIn    ICQ 11923872