I want to know if a class can inherit from a class and an interface. The example code below doesn't work but I think it conveys what I want to do. The reason that I want to do this is because at my company we make USB, serial, Ethernet, etc device. I am trying to develop a generic component/interface that I can use to write programs for all our devices that will help keep the common things (like connecting, disconnecting, getting firmware) the same for all of our applications.
To add to this question: If GenericDevice is in different project, can I put the IOurDevices interface in that project then then make the USBDevice class implement the interface if I add a reference to the first project? Because would like to just reference one project and then implement different interfaces depending on what the device is.
class GenericDevice
{
private string _connectionState;
public connectionState
{
get{return _connectionState; }
set{ _connectionState = value;}
}
}
interface IOurDevices
{
void connectToDevice();
void DisconnectDevice();
void GetFirmwareVersion();
}
class USBDevice : IOurDevices : GenericDevice
{
//here I would define the methods in the interface
//like this...
void connectToDevice()
{
connectionState = "connected";
}
}
//so that in my main program I can do this...
class myProgram
{
main()
{
USBDevice myUSB = new USBDevice();
myUSB.ConnectToDevice;
}
}
Yes. Try:
class USBDevice : GenericDevice, IOurDevice
Note: The base class should come before the list of interface names.
Of course, you'll still need to implement all the members that the interfaces define. However, if the base class contains a member that matches an interface member, the base class member can work as the implementation of the interface member and you are not required to manually implement it again.