Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use decimal values as attribute params in c#?

I've been trying to use decimal values as params for a field attribute but I get a compiler error.

I found this blog post link saying it wasn't possible in .NET to use then, does anybody know why they choose this or how can I use decimal params?

like image 962
rjlopes Avatar asked Feb 03 '09 15:02

rjlopes


2 Answers

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.

like image 166
JaredPar Avatar answered Oct 13 '22 18:10

JaredPar


I have the same problem. I consider to use strings. This is not type-safe, but it's readable and I think we will be able to write valid numbers in strings :-).

class BlahAttribute : Attribute {   private decimal value;    BlahAttribute(string number)   {     value = decimal.Parse(number, CultureInfo.InvariantCulture);   } }  [Blah("10.23")] class Foo {} 

It's not a beauty, but after considering all the options, it's good enough.

like image 27
Stefan Steinegger Avatar answered Oct 13 '22 19:10

Stefan Steinegger