3

I got that error with this code:

const string body = HighPoint; // HighPoint is a string arg passed in to the method

...and was able to work around it by removing the constant:

string body = HighPoint; 

...or, of course, assigning a constant value:

const string body = "My Dinner with Andre";

...but is "my way not a very sporting way"? (gratuitous Princess Bride reference)

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • Basically you are looking for a readonly local, and that is not a feature that C# supports. – Anthony Pegram Jul 11 '12 at 03:58
  • Related: http://stackoverflow.com/questions/443687/why-does-c-sharp-disallow-readonly-local-variables – Anthony Pegram Jul 11 '12 at 04:01
  • I guess what's strange to me is that somebody would make something like this const in the first place. I derived this code from a sample on sending email. When would you ever have the same exact body in an email (unless you were a spammer maybe)? – B. Clay Shannon-B. Crow Raven Jul 11 '12 at 04:54

2 Answers2

6

The keyword const in C# means a compile-time constant. It is different from C++ and C, where the same keyword requires only a run-time const-ness.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
5

const in C# is different from const in C++.

In C++, const a runtime constant. The following operations are valid in C++

i.e

const char *CONST_INFO = "hello world";
CONST_INFO = "goodbye world"; //aok
const int i = SomeMethod(); //aok

C#, on the other hand, is stricter. The constant value must be constant at compile time; no method returns or static class members.

If you need to use a one-off value as a constant (i.e an array, or a method return) you can use the static and readonly modifiers to emulate most of the restrictions the const keyword gives you:

public static readonly string body = HighPoint;

Should compile fine, and you'll still exprience similar restrictions with modifying the value as you would with const

Jason Larke
  • 5,289
  • 25
  • 28