tags:

views:

523

answers:

10
+3  Q: 

Space code in C#

Not literally code from space however:

I'm wondering if there's a more OO way if creating spaces in C#.

I currently have tabs += new String(' '); and I can't help but feel that this is somewhat reminiscent of using '' instead of String.Empty.

What can I use to create spaces that isn't ' '?

+13  A: 

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';
        }
    }
}
dtb
In my actual code I'm doing new String(' ',numberOfSpaces) so I probably need to still use the new String part.
Jamie Dixon
@Jamie: It would have been useful to say that to start with, as it makes basically all the existing answers invalid.
Jon Skeet
Yeah appologies for that. I think other people might have this question at some point, and those people might not be specifying the number of spaces so I think these answers will be useful for them.
Jamie Dixon
Thanks dtb. I had to accept this one, not only because you answered the question at the top, but also for your use of the terms "SpaceFactory" and "enterprisey".
Jamie Dixon
dailywtf candidate
axel_c
wow...just for a space?
TStamper
I regret that I can only vote this up once
Gabe Moothart
+3  A: 

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);
Austin Salonen
+5  A: 

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);
TStamper
Nice, but I'd use String.Empty to satisfy his dislike of strings in code!
Philip Wallace
Or use the string constructor that takes a character count instead: `return new string(' ', count);`
LukeH
+2  A: 

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.

Mark Dickinson
+1 - extension methods seem to be in line with the OP's style here. Note you can replace the body of this function with `return new String(' ', count);` as this overloaded constructor does exactly what you've done :)
John Rasch
Even though an extension method may be desired, there's no need to use repeated string concatenation like this. "return text + new string(' ', size)" would be more appropriate IMO. (Having changed the first parameter from the keyword `string` to `text`...)
Jon Skeet
Thanks John and Jon (sorry Tony). Yes that feels much better, being a web bod I rarely want to have two spaces next to each other anyway, just thought I'd add my two pence worth.
Mark Dickinson
+3  A: 

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.

Gabe Moothart
A: 

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.

avid
+3  A: 

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)
Jon Skeet
+1  A: 

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.

corymathews
+1  A: 

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));
}
Christian Hayter
Thanks Christian. The larger problem i'm solving is that I've got an IEnumerable of objects with an Id and ParentId. I'm outputting the contents of these objects to CSV format for data export and need to show the relationship between the objects. On the screen they're shown as a Tree grid and for export I'm spacing them to show the relationship.
Jamie Dixon
A: 

You could use "\t", I think, to give you a tab character. That might make the spaceing more clear.

Matt Ellen