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
1
: 747 At:- 1/15/2018 3:44:10 PM
C# string c# insert variables into string c# string inline variable






1 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





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