Symbols in .NET

This post was imported from blogspot.

I'm a big fan of Ruby's "symbols". Symbols are sort of like strings or enums, but different. Their syntax is an identifier with a colon in front, e.g. :Foo. See here for details.

I love using symbols in place of enums, because if they are implemented properly, comparing two symbols is as fast as comparing two integers (enums). Enums have the problem of non-extensibility; library B can't define new values for an enum in library A. Meanwhile, anybody can define a new symbol at any time.

Via Loyc I would like to add symbol support to C# and boo, but Loyc is a long way off as long as I have nobody to help me. In the meantime, see here for my current implementation of Symbols in C#.

To simulate enums using Symbols in C#, I just define a static class full of Symbols. For example:
public static class Tokens {
  static public readonly Symbol WS = Symbol.Get("WS"); // whitespace
  static public readonly Symbol NEWLINE = Symbol.Get("NEWLINE");
  static public readonly Symbol ID = Symbol.Get("ID"); // identifier
  static public readonly Symbol PUNC = Symbol.Get("PUNC");
  static public readonly Symbol EOS = Symbol.Get("EOS");
  static public readonly Symbol ML_COMMENT = Symbol.Get("ML_COMMENT");
  static public readonly Symbol SL_COMMENT = Symbol.Get("SL_COMMENT");
  ...
}
Enjoy!