3

Given the following code:

string a = "example"; string b = "blah {0}", a; 

I was led to believe that using {0} or {1}, that it would put whatever is after the comma, in this case string a, so "example". String b should be "blah example". When I do this I get the error "string a is already declared".

Why does it think that I'm declaring a string in this context?

1
  • You need to use the String.Format function. Alas, C# has no language syntax for string interpolation, cf. Ruby "There are #{apples.count} fruit" or Python "There are %s fruit" % apples.count" Commented Mar 20, 2013 at 18:33

7 Answers 7

9

I believe you are intending to use string.Format. It's not implied (but it would be nice).

string b = string.Format("blah {0}", a); 

Your code would translate like below. The compiler error is obvious when you expand it out fully.

// Given string a = "example"; string b = "blah {0}", a; // corresponds to ... string a; a = "example"; string b; b = "blah {0}"; string a; 

MSDN Local variable declaration

Sign up to request clarification or add additional context in comments.

Comments

5

This line:

string b = "blah {0}", a; 

declares string b with an initial value, and then declares string a.

When you specify multiple variable names separated by a comma, it declares them all, e.g.:

string a, b, c, d; 

You probably meant to use String.Format().

string b = String.Format("blah {0}", a); 

1 Comment

Thanks for the answer oO didn't even know about "String.Format" thing
5

enter image description here

looks like you're trying to use String.Format

string b = String.Format("blah {0}", a); 

Think of it as a method that builds your string for you. kinda like printf from c/c++

Comments

2

You are re-declaring a.

In c# and many other languages, it's short hand to declare variables using a comma delimeter.

Example:

int x,y,z; // declare three integer variables x y and z 

You need to use String.Format

string a = "example"; string b = string.Format("blah {0}", a); 

Comments

2

You are just redeclaring the variable as Eric. J said. Looks like you are trying to connect two strings, so you can use Format function from string class:

string a = "example"; string b = string.Format("blah {0}", a); 

or you can use an operator +:

string a = "example"; string b = "blah " + a; 

Good luck ;).

Comments

1

This is what you're looking for:

string b = string.Format("blah {0}", a); 

Comments

1

string b = string.Format("blah {0}", a);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.