Identifiers in C# or Morse Code API

We all new that the underscore (‘_’) was a valid character in C# identifiers but what I didn’t know is that it is legitimate to have nothing but underscore characters. I found this out while doing some code generation and identifier scrubbing. By that I mean if you are trying to create class names or namespaces based on user input you have to scrub out invalid characters and I chose to replace them with underscores.

I decided to mess around with this and I came up with a quick Morse Code API based on my misuse of underscore identifiers.

// SOSConsole.WriteLine("Transmitting: SOS");
Morse.Code._._._.o.___.___.___.o._._._.Play();
Symbol Name
._ dit
.___ dah
.o. Letter
.ooooo. Word

So, SOS above is “dit dit dit, dah dah dah, dit dit dit”. It plays by using Console.Beep and letter and word boundaries use Thread.Sleep. Here’s a more complicated example taken from wikipedia!

Console.WriteLine("Transmitting: Morse Code");
Morse.Code.
//         1         2         3         4         5         6         7         8
//12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789

//M------   O----------   R------   S----   E       C----------   O----------   D------   E
//===.===...===.===.===...=.===.=...=.=.=...=.......===.=.===.=...===.===.===...===.=.=...=  
  ___.___.o.___.___.___.o._.___._.o._._._.o._.ooooo.___._.___._.o.___.___.___.o.___._._.o._
//        ^               ^    ^       ^             ^
//        |              dah  dit      |             |
//   symbol space                letter space    word space.Play();

It actually sounds pretty good!

Download:

Non-generic Enum.TryParse

It turns out that there isn’t a non-generic TryParse overload in .net 4. This seems like a pretty egregious oversight so I created my own.

public static class EnumHelper
{
    static MethodInfo enumTryParse;

    static EnumHelper()
    {
        enumTryParse = typeof(Enum).GetMethods(BindingFlags.Public | BindingFlags.Static)
            .Where(m => m.Name == "TryParse" && m.GetParameters().Length == 3)
            .First();
    }

    public static bool TryParse(
        Type enumType, 
        string value, 
        bool ignoreCase, 
        out object enumValue)
    {
        MethodInfo genericEnumTryParse = enumTryParse.MakeGenericMethod(enumType);

        object[] args = new object[] { value, ignoreCase, Enum.ToObject(enumType, 0) };
        bool success = (bool)genericEnumTryParse.Invoke(null, args);
        enumValue = args[2];

        return success;
    }
}

enjoy.