Home
C# String Interpolation or Curley Brackets
Blog Date 4 June 2021
The Code Behind
using System;
public partial class xxx : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string[] x = { "Andy", "Sarah", "Sally Smith" };
MyShow.Text = $"Hello {x[0]} and {x[1]} and also {x[2]}";
MyShow.Text += "<br />";
MyShow.Text += $"Shorten {x[2]} to {x[2].Substring(0, 5)}";
MyShow.Text += "<br />";
MyShow.Text += $"UpperCase {x[1].ToUpper()}";
}
}
The ASPX HTML Page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="xxx.aspx.cs" Inherits="xxx" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="MyShow" runat="server" />
</div>
</form>
</body>
</html>
The Explanation
I've come across "Interpolation" before watching a Javascript coder. I wasn't sure if it worked in C# but it does. It's not absolutely necessary, it's one of them "there's many ways to skin a cat" things.
You can build a string as I've always done like this...
string qwe = "Hello " + Input.Text + " to this website";
...and there's nothing wrong with that at all. Interpolation is just a bit quicker and, depending on your preference, a little easier to read.
string qwe = $"Hello {Input.Text} to this website";
It's also worth noting that you can do all the regular manipulations WITHIN the curly brackets. If you wish to actually print/show some curly brackets these can be escaped by using 2 or them together
string qwe = $"Brackets are escaped thus {{ and }}"
Need a nerd? Contact ren@techsolus.co.uk
Reader's Comments
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home