Alan2
Alan2

Reputation: 24562

Is there a way I can create a string out of some text and a parameter list?

What I would like to do is something like this:

 var a = "Hello 123";

but instead code it like this:

 var id = 123;
 var a = xxxx("Hello ?", id);

Is there some function I can replace the xxxx with that will help me to do this in C#

Upvotes: 0

Views: 54

Answers (4)

Kvam
Kvam

Reputation: 2218

You can either concatenate using +:

var a = "Hello " + id;

string.Format:

var a = string.Format("Hello {0}", id);

or string interpolation:

var a = $"Hello {id}";

Upvotes: 2

Jonatan Dragon
Jonatan Dragon

Reputation: 5017

var id = 123;
var a = $"Hello {id}";

Upvotes: 2

Adrian
Adrian

Reputation: 8597

There is.

String.Format("Hello {0}", id);

String format uses numbered indexes to bind data into the string.

And as of C# 6 onwards you can use the following string interpolation:

var a = $"Hello {id}";

Upvotes: 4

bommelding
bommelding

Reputation: 3037

If I take that literally, replacing the ?:

 string a = "Hello ?".Replace("?", id.ToString());

but normally we do

 string a = String.Format("Hello {0}", id);

or

 string a = $"Hello {id}";

Upvotes: 2

Related Questions