Reputation: 856
I have function where I want display a number in text.
if (all > 120)
{
int w_m = 120 - il_os;
string text = "free room: {0}", w_m;
ModelState.AddModelError("", text);
}
but I have a error:
Error 1 A local variable named 'w_m' is already defined in this scope
how display number with text in ModelState.AddModelError?
Upvotes: 1
Views: 486
Reputation: 754565
You need to use String.Format
in order to format strings in that manner
string text = String.Format("free room: {0}", w_m);
Doing this will also remove the error you're seeing because the current syntax you're using is causing w_m
to be redeclared as a string
local.
Upvotes: 3
Reputation: 19416
use String.Format which will be used like this:
string text = String.Format("free room: {0}", w_m);
Edit: Beaten to it, Should have known finding the MSDN link would cost me those precious seconds.
Upvotes: 0
Reputation: 224857
You're missing a function there:
string text = string.Format("free room: {0}", w_m);
Placeholders in strings isn't a language feature! Right now you're declaring the variable w_m
again, as a string
. That is a feature:
int a, b, c;
Upvotes: 3
Reputation: 22379
string text = string.Format("free room: {0}", w_m);
In your code the compiler thinks that w_m is another declaration, as in:
string a, b;
Upvotes: 0
Reputation:
Your error has nothing to do with displaying a number in text. You are declaring a variable (w_m
) that is already in that scope.
w_m
must be declared prior to your if
clause. If you are looking to reuse your w_m
variable, then change the above line to:
w_m = 120 - il_os;
As for putting that number in your string, you can do a couple of things:
string text = "free room: " + w_m.ToString();
Or
string text = string.Format("free room: {0}", w_m);
Upvotes: 0