How to insert C# variable value in between string properly?


Hello, I am trying to pass this string from back-end C# to front end, and want to render it as HTML, when passing this string to the front-end, it doesn't look proper, here is my current C# code.

var str="<span href='/ShowQuote/" +QID+ "?NewTab=True' style='margin: 10px; text-decoration:none' class='ShowQuoteClick'>Fetched one quote for " + MainCompanyName + " with Id-" + Id + "</span>";

in the above code QID, MainCompanyName & Id is C# variables, so how can I insert variable values in the middle of a string properly, using C#?


Asked by:- Vipin
3
: 6542 At:- 1/15/2018 3:44:10 PM
C# string c# insert variables into string c# string inline variable







3 Answers
profileImage Answered by:- jaya

Here are the ways to insert C# variable in between a string:

  1. Using string.Format
    var str="<span href='/ShowQuote/{0}?NewTab=True' style='margin: 10px; text-decoration:none' class='ShowQuoteClick'>Fetched one quote for {1} with Id-{2}</span>";
    var newStr=string.Format(str, QID,MainCompanyName,Id);?
  2. Using C# 6.0 String Interpolation
    var QID= "1";
    var MainCompanyName = "Test";
    var Id="11";
    var str = $"<span href='/ShowQuote/{QID}?NewTab=True' style='margin: 10px; text-decoration:none' class='ShowQuoteClick'>Fetched one quote for {MainCompanyName} with Id-{Id}</span>";
    
2
At:- 1/17/2018 8:50:15 AM


profileImage Answered by:- vikas_jk

You can check the detailed article on C# String Interpolation here or about C# Strings

Basically, you can format strings using String.Format as sample is provided in above answer.

            string name = "Vikas";
            string developer = ".NET Developer";
            Console.WriteLine(String.Format("Hi my name is {0}, working as {1}",
                                          name, developer));

Hope it helps.

1
At:- 12/10/2020 11:49:51 AM


profileImage Answered by:- Vinnu

To insert a variable in string, simple use below code

string FirstValue = "value1";
string SecondValue = "value2";
Console. WriteLine("{0} and {1}", FirstValue, SecondValue);

You can also use string.replace if you want to insert it in between

var sample = "My String #replace# Words";
var result = sample.Replace("#replace#", Var1);

That's it.

1
At:- 5/27/2022 7:48:24 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use