Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a constant decimal value

Tags:

I'm using C# to set a default value for a decimal value in my config class

public class ConfigSection : ConfigurationSection
{
        [ConfigurationProperty("paymentInAdvanceAmount", **DefaultValue = 440m**)]
        public decimal PaymentInAdvanceAmount
        {
            get { return (decimal)base["paymentInAdvanceAmount"]; }
            set { base["paymentInAdvanceAmount"] = value; }
        }
}

but it won't be compiled and throws an error

An attribute argument must be a constant expression, typeof expression

I found a post says: "It's not a bug. "1000M" is merely shorthand for "new Decimal(1000)", which involves a method call, which means it's not considered a constant. Just because the compile lets you pretend it's a constant most of the time, doesn't mean you can all of the time."

Now, how do I workaround it?

like image 718
ldsenow Avatar asked Aug 06 '09 00:08

ldsenow


2 Answers

I finally found out it I enter "440" instead of 440m or 440. It got compiled and runs well

like image 181
ldsenow Avatar answered Oct 12 '22 13:10

ldsenow


I found that if you set a default value for a decimal property and specified that value in quotes, it did not work for me with a WinForms control and .NET 3.5.

When ever I right clicked on the property in the designer "Properties" window and selected the "Reset" option I got the message "Object of type 'System.String' cannot be converted to type 'System.Decimal'.

To get it to work I had to use the same code as tphaneuf suggested i.e.

[DefaultValue(typeof(Decimal), "440")]
public decimal TestValue { get; set; }
like image 42
user461707 Avatar answered Oct 12 '22 15:10

user461707