Click here to Skip to main content
15,889,878 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Please help me to const string value at runtime

here,i want to change "cWeatherID" in loop

What I have tried:

public partial class Form1 : Form
{


const string cWeatherID


private void button1_Click_1(object sender, EventArgs e)
      {

foreach (string s in listBox2.Items)
{


cWeatherID =s

const string lURL = cURL + "?" + cWeatherID + "&" + cUnitID + "&format=" + cFormat;
?
}
}
Posted
Updated 5-Feb-20 21:00pm
Comments
F-ES Sitecore 6-Feb-20 4:38am    
Just to add to what the others have said, constants aren't variables even though they look like them. If I write this code;

const x = 5;
int y = 2 * x;

then what is actually compiled is

int y = 2 * 5;

The compiler does a literally replacement of everywhere you use "x" with "5". That's why you can't change a constant at run time; they don't exist at run time, only compile time.

You cannot. A constant is... constant.
If you want the variable to be mutable, do not define it as constant.
const keyword - C# Reference | Microsoft Docs[^]
 
Share this answer
 
v2
The const keyword is there to explicitly say "this will always have the value I give it now: it cannot be changed by anyone, ever" and the system will enforce that. But looking at your code, why would you need it at all? Change to this:
C#
foreach (string cWeatherID in listBox2.Items)
    {
    string lURL = cURL + "?" + cWeatherID + "&" + cUnitID + "&format=" + cFormat;
    ...
    }
Or better (if you use a recent version of VS)
C#
foreach (string cWeatherID in listBox2.Items)
    {
    string lURL = $"{cURL}?{cWeatherID}&{cUnitID}&format={cFormat}";
    ...
    }
And it should start to work.
 
Share this answer
 
Quote:
How can we change the value of a constant at run time?

You don't, it is the principle of constant.
The keyword constant is used explicitly to say that the value never change at runtime. And any attempt to do so is reported as an error at compile time.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900