28 December 2010

Enum values can be characters too

Almost everyone who has programmed something in C# has created an enum at one point or another:

public enum Whatever
You can cast an enum value to an int - you then get a value assigned by the compiler based upon the order in the enum, so Zero will be 0, One will be 1, etc. If you have a particular sick mind you can add a new chapter to How to write unmaintainable code by creating something like
public enum Whatever
  One = 5,
  Two = 3,
  Three = 2
But you can also assign values to it using characters. This way, I have created an enumeration that can be used to retrieve tiles from Google servers based upon their enum value without the switch I wrote in my infamous "Google Maps for Windows Phone 7" article. So now you can define the server on which Google stores a particular tile type like this:
public enum GoogleType
  Street         ='m',
  Hybrid         ='y',
  Satellite      ='s',
  Physical       ='t',
  PhysicalHybrid ='p',
  StreetOverlay  ='h',
  WaterOverlay   ='r'
and then determine the server like this:
var server = string.Format("http://mt{0}.google.com", (char)GoogleType.Street);

This makes far cleaner code.

No comments: