C# string must be a constant [duplicate] - c#

This question already has answers here:
Why does interpolating a const string result in a compiler error?
(6 answers)
Closed 3 years ago.
I was writing this piece of code:
public const int MAJOR_VERSION = 3;
public const int MINOR_VERSION = 3;
public const string VERSION_STRING = $"v.{MAJOR_VERSION}{MINOR_VERSION}";
And, maybe not surprisingly, the compiler was complaining:
"The expression being assigned to VERSION_STRING must be constant"
I understand that const expressions are meant to be propagated by the compiler, but in this particular case, the string can very easily be statically created because it depends only on other constants.
So perhaps someone can explain to me why this is not already a feature of the language?
Or maybe even, why it's silly of me to ask such a question..
Thanks in advance. :)

You have this error because the $ symbol in front of a string is a shortcut for calling String.Format(). String.Format() being a method, its return value cannot be stored in a constant.

When we use const keyword, then the values of string interpolation must be a compile-time constant. Using a string interpolation requires .NET code to execute which can only occur when the application is running, not during compile time.
So instead of const you can use static readonly:
public const int MAJOR_VERSION = 3;
public const int MINOR_VERSION = 3;
public static readonly string VERSION_STRING = $"v.{MAJOR_VERSION}{MINOR_VERSION}";

The string you are trying to set is not a constant value, because it is derived from other variables/constants.
Try static readonly instead
public static readonly string VERSION = $"v.{MAJOR_VERSION}{MINOR_VERSION}";

To explain why the C# team couldn't have made this a compile time feature:
The result of $"{}" or string.Format() can vary at runtime depending on the culture of the machine it's running on at the time.
For example see here that the VERSION is a constant but the resulting strings are different.
const double VERSION = 3.3;
string withDots = String.Format(new System.Globalization.CultureInfo("en-GB"), "{0:N}", VERSION));
// "3.3"
string withCommas = String.Format(new System.Globalization.CultureInfo("fr-FR"), "{0:N}", VERSION));
// "3,3"

Related

why can't I define a non printable character as constant c#

private const string requireNonPrintableChar = new string('\x0005', 1);
I do not expect this value to change. I was told once upon a time it's good practise to use const for values you don't expect to change.
However msbuild is saying:
"Error 1 The expression being assigned to requireNonPrintableChar' must be constant"
am assuming that char doesn't count as a const but why?
The msdn says it can be a string which I believe it is.
Simply do:
private const string requireNonPrintableChar = "\x0005";
new string('\x0005', 1) is an expression that does get evaluated to a string, but it is not a compile-time constant, and const fields can only be assigned values which can be evaluated at compile time.
A constant has to be defined directly. You can't use functions to get your const value.
Instead of doing this
const string MY_CONST = test();
static string GetValue()
{
return "Hello";
}
You should do this
const string MY_CONST = "Hello";
If you want to use method initialization you could use static readonly like this
private static readonly string requireNonPrintableChar = new string('\x0005', 1);
Source
You can do what w0lf said:
private const string requireNonPrintableChar = "\x0005";
But if you want your second paramter for cound, use:
private static readonly string requireNonPrintableChar = new string('\x0005', 1); // should be greater than 1

convert variable to constant

Can seems to be strange, but is there a way to declare or convert variable to constante something like :
string myVariable = "MyString";
const string myConstant = myVariable ;
I need this to answer to my problem:
linq to sql startwith performance indexed columns
thanks
no there is no way to do this for Const Const values are burned directly into the call-site at compile time, Instead you could make it readonly and assign it in the constructor
something like
string myVariable = "MyString";
readonly string myConstant="test" ;
public MyClass()
{
myConstant= myVariable ;
}
No, you cannot initialize a constant using the value of a variable.
Constants must be known at compile time, and the value of a variable is not known until runtime, making it conceptually impossible.
Otherwise, change your first variable to a constant like below :
const string myVariable = "MyString";
const string myConstant = myVariable ;
No, you can't use a variable to initialize a field. The compiler may re-arrange the order these are initialized in, myConstant could be initialized first, in which case myVariable would be not be set.
Constants cannot vary because they are not variables setting it to a variable would be varying it. So the answer is no at least not at runtime.
Maybe you just want something that can't be set many places then readonly might work.
reference: http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx
public readonly string _myROString = "set once";
Well is not possible. But someone find an answer to my initial question without constant. thanks
linq to sql startwith performance indexed columns
This answer does not provide solution to the question posted; But may satisfy the requirement for some viewers who like to access string in a static manner which should be appended with other strings,
public enum NameTypes
{
First, Last
}
public static class UserDetails
{
public static string NameText = "Name Info: " + NameTypes.First.ToString();
}

The Expression assigned to X must be constant? [duplicate]

This question already has answers here:
CS0133 "The expression being assigned to 'identifier' must be constant" - what's the reason behind that?
(4 answers)
Closed 9 years ago.
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)
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.
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

order initializiation static parameter

Is there any specification for the order in which static readonly parameters are initialized?
In the following example, can one be sure, the array is always created with a length of 6?
public class Foo {
private static readonly int MAX_STACKSIZE = 6;
private static readonly int[] m_stack = new int[MAX_STACKSIZE];
}
Or is there any chance of m_stack being initialized before MAX_STACKSIZE ?
#Edit: changed const to static readonly
EDIT: This answer was written when the sample code contained "const" instead of "static readonly". It's not valid for the current version of the question - I may write another answer to deal with that at some point, but I don't have time right now.
That won't be valid C# anyway, as you can't set a const int[] to anything other than null.
However, in the more general case, section 10.4 of the C# spec applies:
Constants are permitted to depend on other constants within the same program as long as the dependencies are not of a circular nature. The compiler automatically arranges to evaluate the constant declarations in the appropriate order.
It then gives the following example:
class A
{
public const int X = B.Z + 1;
public const int Y = 10;
}
class B
{
public const int Z = A.Y + 1;
}
and says...
the compiler first evaluates A.Y, then evaluates B.Z, and finally evaluates A.X, producing the values 10, 11 and 12 in that order.

How can this not be a constant value?

I know this is probably just a terminology mismatch but if i'm not mistaken i believe c# is? unless i'm missing something obvious??
...
private const uint URL_COUNT = 18;
private string[] _urls;
public Redirector()
{
this._urls = new string[URL_COUNT];
...
}
...
Results in “A constant value is expected “ and underlines URL_COUNT in the array definition??
Whats URL_COUNT if it isn’t a const -ant value?!?!
EDIT
Phew, i thought for a second then i was going mad. I'm glad no one could repro this as that means it's just a local thing.
Thanks for your help guys.
This will only fail to compile when you supply both the dimension lengths and an array initializer. For example:
this._urls = new string[URL_COUNT];
will be fine, but:
this._urls = new string[URL_COUNT] { "One", "Two" };
will not. The latter requires a constant expression. Note that a const variable is not a constant expression, just a constant value. From the C# specification (3.0) par 12.6:
When an array creation expression
includes both explicit dimension
lengths and an array initializer, the
lengths must be constant expressions
and the number of elements at each
nesting level must match the
corresponding dimension length.
It is a constant and should work fine. The following code compiled fine for me with the C# 3 compiler:
using System;
class Foo
{
private const uint URL_COUNT = 18;
private string[] _urls;
public Foo()
{
this._urls = new string[URL_COUNT];
}
}
This works too, without any complaints from the compiler.
class Foo {
private const uint URL_COUNT = 18;
private readonly string[] _urls = new string[URL_COUNT];
}

Categories

Resources