One good use I have found for extension methods in C# is providing object.verb methods for enums.
public static int ToInt(this BaudRate baudRate)
{
switch (baudRate)
{
case BaudRate.BaudUnsupported:
return 0;
case BaudRate.Baud1200:
return 1200;
case BaudRate.Baud2400:
return 2400;
case BaudRate.Baud4800:
return 4800;
case BaudRate.Baud9600:
return 9600;
case BaudRate.Baud19200:
return 19200;
case BaudRate.Baud38400:
return 38400;
case BaudRate.Baud57600:
return 57600;
case BaudRate.Baud115200:
return 115200;
case BaudRate.Baud230400:
return 230400;
default:
throw new ArgumentOutOfRangeException("baudRate");
}
Not exactly the best example (and not necessarily the best way to do that), but it's a quick one. public enum AnchorFace
{
/// <summary>0</summary>
XLow,
/// <summary>1</summary>
XHigh,
/// <summary>2</summary>
YLow,
/// <summary>3</summary>
YHigh,
/// <summary>4</summary>
ZLow,
/// <summary>5</summary>
ZHigh
}
public static class AnchorFaceHelper
{
/// <summary>Normal Vector for the face</summary>
public static Vector3D GetNormalVector(this AnchorFace self)
{
switch (self)
{
case AnchorFace.ZLow:
return new Vector3D(0, 0, -1);
case AnchorFace.ZHigh:
return new Vector3D(0, 0, 1);
case AnchorFace.YLow:
return new Vector3D(0, -1, 0);
case AnchorFace.YHigh:
return new Vector3D(0, 1, 0);
case AnchorFace.XLow:
return new Vector3D(-1, 0, 0);
default: // XHigh
return new Vector3D(1, 0, 0);
}
}
}