Very useful and handy String constructor, String(Char, Int32)

String Constructor - strings of repeated charachterWe all work with string values in our daily programming life. Sometimes we might require a string variable to be initialized with strings of a repeated character.

Now let us come to the point.

.NET Framework String class already have a parameterized constructor to do the same.

String Constructor (Char, Int32)

C# Syntax:


public String(
 char c,
 int count
 )

MSDN: “Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.”

See the sample usage given below,

class Program
{
	static void Main(string[] args)
	{
		int size = 10;

		string sample = new String('-', size);

		Console.WriteLine(sample);

		Console.ReadKey();

		//Outputs : ----------
	}
}

This is the most straightforward and efficient way to initialize a string variable with strings of repeated characters.

Advertisements

One thought on “Very useful and handy String constructor, String(Char, Int32)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s