34

Is this an appropriate way to handle c# switch statements or is an explicit break required still? reference

  public static string ToRegistryString(AliceKey.AliceKeyPaths aliceKeyPath)
    {
     switch (aliceKeyPath)
        {
            case AliceKey.AliceKeyPaths.NET_CLR_DATA:
                return @"\.NET CLR Data\";
            case AliceKey.AliceKeyPaths.NET_CLR_NETWORKING:
                return @"\.NET CLR Networking\";
            case AliceKey.AliceKeyPaths.NET_DATA_PROVIDER_MSSQL:
                return @"\.NET Data Provider for SqlServer\";
            case AliceKey.AliceKeyPaths.NET_DATA_PROVIDER_ORACLE:
                return @"\.NET Data Provider for Oracle\";
         }
       return new string(new char[0]);
     }
Community
  • 1
  • 1
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
  • 1
    Instead of putting "return new string(new char[0]);" outside the switch statement you could also use the "default: return new string(new char[0]);" case after all the other cases. It will be a cleaner way to use the Switch statement. – FrozZerrer Oct 25 '17 at 17:59

2 Answers2

44

That's fine. The point is that the end of a case block should be unreachable - which it is here, because you've returned.

Why are you returning new string(new char[0]) rather than just "" or string.Empty though? If you're trying to make sure it's a different string each time, you'll actually run into a very weird corner case - despite calling new string(...) that code will always actually return the same reference...

Finally: I would actually suggest changing this switch/case block into just a Dictionary<AliceKey.AliceKeyPaths, string>:

private static readonly Dictionary<AliceKey.AliceKeyPaths, string> RegistryMap =
    new Dictionary<AliceKey.AliceKeyPaths, string>
{
    { AliceKey.AliceKeyPaths.NET_CLR_DATA, @"\.NET CLR Data\" },
    { AliceKey.AliceKeyPaths.NET_CLR_NETWORKING, @"\.NET CLR Networking\" },
    // etc
};

public static string ToRegistryString(AliceKey.AliceKeyPaths aliceKeyPath)
{
    string value;
    return RegistryMap.TryGetValue(aliceKeyPath, out value) ? value : "";
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

You do not need to specifically use a break statement just one that changes the flow of control, so a goto or a return should work.

See MSDN for more info: http://msdn.microsoft.com/en-us/library/06tc147t(VS.71).aspx

Jordan
  • 4,928
  • 4
  • 26
  • 39