-1

I am using an online convert tool to convert the VB Codes to C#. The VB codes are:

Private Const constant1 As Decimal = CDec(37.5)

result:

private const decimal constant1 = Convert.ToDecimal(37.5);

However, there is an error message when compiling:

The expression being assigned to 'constant1' must be constant

In order to remove the error, I amended the codes as:

private const decimal constant1 = (decimal)37.5;

Can anyone advise why the Convert.ToDecimal couldn't return a Constant?

DennisL
  • 293
  • 1
  • 3
  • 12

3 Answers3

4

You don't need Convert.ToDecimal (or CDec) here, if the value you're converting itself is constant.

You can simply write:

private const decimal constant1 = 37.5m;
Rob
  • 26,989
  • 16
  • 82
  • 98
2

When constants are compiled, the actual value is stored in the assembly's metadata. This means that it cannot be changed at all at runtime. In fact, consuming assemblies assume it never changes and compile the value into their metadata as well.

When you use Convert.ToDecimal(), you are executing runtime code. Therefore, the value cannot be assigned to the constant because running code when compiling the value into the assembly is not possible (at least not without some compiler hacks).

As @AlexD mentioned, if you use a static readonly value you can set it at runtime, because it is not compiled into the assembly.

private static readonly decimal constant1 = Convert.ToDecimal(36.6);
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
1

No, method return values are not compatible with const (because they are, well, not constant, at least not to the compiler). However you can just get rid of the function (and cast!) and use a decimal literal ("m" suffix):

private const decimal constant1 = 37.5m;
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117