0

After searching the web and reading docs on MSDN, I couldn't find any examples of how to replicate a tab character in C#. I was going to post a question here when I finally figured it out...

I'm sure it is obvious to those fluent in C#, but there were SO many similar questions in various forums, I thought an example was worth posting (for those still learning C# like me). Key points:

  1. use "double-quotes" for a string
  2. use 'single-quotes' for a char
  3. \t in a string is converted to a tab: "John\tSmith"
  4. '\t' by itself is like a tab const

Here is some code to add tabs to the front of an HTML line, and end it with a newline:

public static string FormatHTMLLine(int Indent, string Value)
{
  return new string('\t', Indent) + Value + "\n";
}

You could also use:

string s = new string('\t', Indent);

Is this the most efficient way to replicate tabs in C#? Since I'm not yet 'fluent', I would appreciate any pointers.

James L.
  • 9,384
  • 5
  • 38
  • 77

2 Answers2

1

Yes, I think this is the best way.

The string constructor you are using constructs a string containing the character you specify as the first argument repeated count times, where count is the second argument.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

1) You should cache and reuse results from calling new string('\t', Indent). 2) Try not to generate new string from FormatHTMLLine. For example, you can consider write them to output stream.

void IndentWrite(int indent, string value)
{
    if (indent > 0)
    {
       if (s_TabArray == null)
       {
         s_TabArray = new char[MaxIndent];

         for (int i=0; i<MaxIndent; i++) s_TabArray[i]='\t';
       }

       m_writer.Write(s_TabArray, 0, indent);
    }

    m_writer.Write(value);
    m_writer.Write('\n');
}
Feng Yuan
  • 709
  • 5
  • 4
  • 1
    I'm not sure what you're getting at with `s_TabIndentArray`. It seems like you the behavior you intend is for it to be prepopulated with all sorts of indent sizes, and the expected result is that you'll save on creating, for example, `"\t\t"` more than once. That's not really the case, though; the CLR will use string interning to avoid creating multiple copies of the same string itself - http://en.wikipedia.org/wiki/String_interning – Marc Bollinger Aug 17 '12 at 19:30
  • CLR does very limited string interning, not going to help here. Actually, I work on the CLR team. Just changed code to avoid using strings. – Feng Yuan Aug 17 '12 at 21:06
  • @FengYuan good to know. Don't trust The Magic all the time, I suppose. – Marc Bollinger Aug 18 '12 at 00:19