0

I have a set of constant strings which are related to each other:

private const string tabLevel1 = "\t";
private const string tabLevel2 = "\t\t";
private const string tabLevel3 = "\t\t\t";
...

I'm looking for a more elegant way to declare these, something like:

private const string tabLevel1 = "\t";
private const string tabLevel2 = REPEAT_STRING(tabLevel1, 2);
private const string tabLevel3 = REPEAT_STRING(tabLevel1, 3);
...

Is there some preprocessor directive or some other way of achieving this?

P.S. I already know that const string tabLevel2 = tabLevel1 + tabLevel1; workes, probably due to this. I'm looking for the general case for arbitrary n.

EDIT

I wish to clarify why I need const and not static readonly: The constants are used as parameters to a property decorator, e.g. [GridCategory(tabLevel2)], and must be known at compile time.

Community
  • 1
  • 1
bavaza
  • 10,319
  • 10
  • 64
  • 103
  • How many times do you want it to be repeated? I don't think it's important to care about. **constant is something you should feel satisfied even you have to type hundreds lines just to declare them**. `Win32 Constants` is an example. – King King Sep 08 '13 at 15:05

3 Answers3

2

You cannot do that in C#. Also there is no macro preprocessor in c# like in c or c++. Your best bet is to use the following:

private const string tabLevel1 = "\t";
private static readonly string tabLevel2 = new string('\t',2);
private static readonly string tabLevel3 = new string('\t',3);

Hope it helps.

Vinod Kumar Y S
  • 628
  • 3
  • 9
  • thanks, but as Magnus said - your code won't compile. You can't call a method (even a static one), nor use the `new` operator for `const`. The value has to be known at compile time. – bavaza Sep 08 '13 at 15:14
1

Because you require constants for use in attribute definitions and because all constants must be able to be evaluated at compile time the best you can do is either use string literals or expressions that involve other constants and string literals. Another alternative would be to provide an alternative implementation of the attribute that takes, not the string representation of the tab level, but a numeric value for it and, possibly, the tab character.

 public class ExtendedGridCategoryAttribute : GridAttribute
 {
      public ExtendedGridCategoryAttribute(int level, char tabCharacter)
          : base(new string(tabCharacter, level))
      {
      }
 }

 [ExtendedGridCategory(2,'\t')]
 public string Foo { get; set; }
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
0

You can do this

private const int tabCount = 10;
private string[] tabs = new string[tabCount];
void SetTabs()
{
  string tab = "";
  for(int x = 0; x<=tabCount - 1; x++)
  {
    tab += "\t";
    tabs[x] = tab;
  }
}
ismellike
  • 629
  • 1
  • 5
  • 14