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 can write
" "
instead of
new String(' ')
Does that help?
Depending on what you do, you might want to look into the StringBuilder.Append overload that accepts a character and a 'repeat' count:
var tabs = new StringBuilder();
tabs.Append(' ', 8);
or into the string
constructor that constructs a string from a character a 'repeat' count:
var tabs = new string(' ', 8);
Here's an enterprisey OO solution to satisfy all your space generation needs:
public abstract class SpaceFactory
{
public static readonly SpaceFactory Space = new SpaceFactoryImpl();
public static readonly SpaceFactory ZeroWidth = new ZeroWidthFactoryImpl();
protected SpaceFactory { }
public abstract char GetSpace();
public virtual string GetSpaces(int count)
{
return new string(this.GetSpace(), count);
}
private class SpaceFactoryImpl : SpaceFactory
{
public override char GetSpace()
{
return '\u0020';
}
}
private class ZeroWidthFactoryImpl : SpaceFactory
{
public override char GetSpace()
{
return '\u200B';
}
}
}
I think you are taking OO way to far.. A simple addition of a space does not need an entire class.
tabs += new String(' ');
or
tabs += " ";
is just fine.
if the number of spaces would be changing then you could do something like this:
public static string Space(int count)
{
return "".PadLeft(count);
}
Space(2);
If the language allowed for it you could add an extension property to the type String which was Space, something like:
public static class StringExt
{
public static char Space(this String s)
{
get {
return ' ';
}
}
}
but that isn't possible. I think it would be better to keep the space inside the property if it was a localizable thingy, but I think spaces are universal across all languages.
You could use "\t"
, I think, to give you a tab character. That might make the spaceing more clear.
The more "OO" way would be to find a simpler way of solving your larger business problem. For example, the fact that you have a variable named tabs
suggests to me that you are trying to roll your own column alignment code. String.Format
supports that directly, e.g.
// Left-align name and status, right-align amount (formatted as currency).
writer.WriteLine("Name Status Amount");
writer.WriteLine("-------------------- ---------- ----------");
foreach(var item in items) {
writer.WriteLine(string.Format("{0,-20} {1,-10} {2,10:C}", item.Name, item.Status, item.Amount));
}