Is there a "Space(n)" method in C#/.Net?

I'm converting an ancient VB6 program to C# (.Net 4.0) and in one routine it does lots of string manipulation and generation. Most of the native VB6 code it uses have analogues in the C# string class, e.g., Trim(). But I can't seem to find a replacement for Space(n), where it apparently generates a string n spaces.

Looking through the MSDN documentation, there seems to be a Space() method for VB.Net but I couldn't find it mentioned outside of a VB.Net context. Why is this? I thought all the .Net languages share the same CLR.

Does C# or .Net have a generic Space() method I can use in C# that I'm just overlooking somewhere?

N.B. I'm aware that writing one-liners to generate n-spaces is a popular quiz-question and programmers' bar-game for some programming languages, but I'm not looking for advice on that. If there's no native way to do this in C#/.Net it's easy enough to write a simple method; I just don't want to reinvent the wheel.


Solution 1:

Use this constructor on System.String:

new String(' ', 10);

http://msdn.microsoft.com/en-us/library/xsa4321w(v=vs.110).aspx

Here's a neat extension method you can use, as well (although it's probably better just to use the String constructor and save the extra method call):

public static class CharExtensions
{
    public static string Repeat(this char c, int count)
    {
        return new String(c, count);
    }
}
...
string spaces = ' '.Repeat(10);

Solution 2:

The string class has a constructor that gives you a string consisting of n copies of a specified character:

// 32 spaces
string str = new string(' ', 32);

Solution 3:

I always use:

var myString = "".PadLeft(n);

Solution 4:

.NET has a set of compatibility functions in the Microsoft.VisualBasic namespace for converting old VB code to .NET, one of them is a recreates the Space function.

var myString = Microsoft.VisualBasic.Strings.Space(10); //Or just Strings.Space(10); if you do "using Microsoft.VisualBasic;" at the top of your file.

However I reccomend using the new String(' ', 10) method the other answers mention.

Solution 5:

I liked GregRos's answer but modified it a bit to make it more declarative and not so dependent on quotation marks where you could accidentally slip in text.

var myString = string.Empty.PadLeft(n);