I\'m wondering if there\'s a more OO way of creating spaces in C#.
Literally Space Code!
I currently have tabs += new String(\" \");
and I can\'
You may create class extensions.
public static class StringExtensions
{
public static string GetSpace(this String)
{
return " ";
}
}
and you can call this.
String.GetSPace();
StringBuilder.Insert and StringBuilder.Append allow you to create any number spaces, e.g. sb.Insert(0, " ", 20) will insert 20 spaces to the start of your sb (StringBuilder) object.
Depending on how prevalent this is in your code, the StringBuilder way may be better.
StringBuilder tabs = new StringBuilder();
...
tabs.Append(" ");
You can mix in the constant too...
StringBuilder tabs = new StringBuilder();
const string SPACE = " ";
...
tabs.Append(SPACE);
Extend string to give you a method to add space
public static string AddSpace(this String text, int size)
{
return text + new string(' ', size)
}
Awful in it's own right though.
Now that you've clarified in comments:
In my actual code I'm doing new String(' ',numberOfSpaces) so I probably need to still use the new String part.
... the other answers so far are effectively useless :(
You could write:
const char Space = ' ';
then use
new string(Space, numberOfSpaces)
but I don't see any benefit of that over
new string(' ', numberOfSpaces)
There is no reason to do this. All else being equal, smaller code is better code. String.Empty
and new String(' ')
communicate the same thing as ""
and " "
, they just take more characters to do it.
Trying to make it 'more OO' just adds characters for no benefit. Object-Orientation is not an end in itself.