Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# How to insert a variable into a string?

Tags:

string

c#

I would like to know the different ways of inserting a variable into a string, in C#.

I am currently trying to insert values into a json string that I am building:

 Random rnd = new Random();
  int ID = rnd.Next(1, 999);
  string body = @"{""currency"":""country"",""gold"":1,""detail"":""detailid-979095986"",""tId"":""help here""}";

How could I add the "ID" to the string body?

like image 637
user3499033 Avatar asked Dec 14 '22 23:12

user3499033


2 Answers

In a typical string inserting scenario, I'd do one of these:

string body = string.Format("My ID is {0}", ID);
string body = "My ID is " + ID;

However, your string is apparently JSON serialized data. I'd expect that I'd want to parse that into a class in order to work with it.

var myObj = JsonConvert.DeserializeObject<MyClass>(someString);
myObj.TID = ID;
// maybe do other things with it, then if I need JSON again...
string body = JsonConvert.SerializeObject(myObj);

One reason to take this approach is to make sure that any data I put in still makes the JSON valid. For example, if my ID were, instead of an int, a string with characters that needed escaping, directly inserting "\"\n\"" would not be the right thing to do.

like image 185
Tim S. Avatar answered Jan 10 '23 02:01

Tim S.


String interpolation is the easiest way these days:

int myIntValue = 123;
string myStringValue = "one two three";
string interpolatedString = $"my int is: {myIntValue}. My string is: {myStringValue}.";

Output would be "my int is: 123. My string is: one two three.".

You can experiment with this sample yourself, over here.

The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6.

like image 43
Tyler S. Loeper Avatar answered Jan 10 '23 02:01

Tyler S. Loeper