public static Connection CreateConnection(string type, string name, int price) { Connection connection; switch (type) { case "WirelessConnection": connection = new WirelessConnection(name, price); break; case "WiredConnection": connection = new WiredConnection(name, price); break; case "DesktopConnection": connection = new DesktopConnection(name, price); break; case "NicConnection": connection = new NicConnection(name, price); break; default: throw new ArgumentException("Unrecognized connection type."); } return(connection); }
/// <summary> /// Creates a <see cref="Connection"/> object. /// </summary> /// <param name="connectionType">The type of the connection to create.</param> /// <param name="price">The price of the <see cref="Connection"/>.</param> /// <returns>A <see cref="Connection"/> object.</returns> /// <exception cref="ConnectionMonitorException">Thrown when an invalid type is requested.</exception> /// <remarks> /// For the built-in <see cref="Connection"/> types /// (i.e. DesktopConnection, NicConnection, WirelessConnection, WiredConnection), /// only the class name is required. For user created types, the fully qualified /// class name is required. /// </remarks> public static Connection CreateConnection(string connectionType, int price) { Guard.StringNotNullOrEmpty(connectionType, "connectionType"); if (price < 0) { throw new ArgumentOutOfRangeException("price"); } Connection connection; switch (connectionType) { case DesktopConnection: connection = new DesktopConnection(DesktopConnection, price); break; case NicConnection: connection = new NicConnection(NicConnection, price); break; case WirelessConnection: connection = new WirelessConnection(WirelessConnection, price); break; case WiredConnection: connection = new WiredConnection(WiredConnection, price); break; default: try { Type connectionTypeToCreate = Type.GetType(connectionType, true); Object createdObject = Activator.CreateInstance(connectionTypeToCreate, connectionTypeToCreate.Name, price); connection = createdObject as Connection; } catch (TypeLoadException ex) { throw new ConnectionMonitorException("Unsupported connection type.", ex); } if (connection == null) { throw new ConnectionMonitorException("Unsupported connection type."); } break; } return(connection); }