A new way to format strings in C# 6

In C# 5 we often format strings with the string.Format function. It requires a format string and then a number of parameters that are passed into the format string. C# 6 has a nice addition which simplifies that syntax.

Let’s start with the following Rockband object:

public class Rockband
{
	public string Name { get; }
	public int NumberOfMembers { get; }
	public decimal ConcertFee { get; }

	public Rockband(string name, int numberOfMembers, decimal concertFee)
	{
		Name = name;
		NumberOfMembers = numberOfMembers;
		ConcertFee = concertFee;
	}

	public string GetFancyName()
	{
		return Name.ToUpper();
	}
}

The fancy name is not too fancy but that’s not important now.

Read more of this post

Advertisement

How to create custom string formatters with C# .NET

.NET has a fairly large number of built-in string formatters that you can pass into the string.Format method. Here are some examples from the MSDN page about formatting:

String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                                city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                                (city.Item5 - city.Item3)/ (double)city.Item3);
String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
                                    "City", "Year", "Population", "Change (%)");
String.Format("{0,-10:C}", 126347.89m);         

The IFormatProvider and ICustomFormatter interfaces will provide you with the methods required to create your own formats.

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: