I’m creating a class to help modify images in a GUI. The images can be in either a PictureBox or a DataGridViewImageCell. The class will store as a list all images that can be modified. Each instance of the class will use either PictureBox or DataGridViewImageCells but not both.
Is there a way to handle both inputs? As in, is there some common interface between them, or a way to cast them to some common parent class?
Well, you can always treat them as
object, but I would suggest that your class simply provide two overloads for those two types specifically:How you store that internally is up to you. Perhaps you have a
List<object>that you cast into/out-of, or perhaps you maintain two separate lists, one for each type, or perhaps you simply add eachimageto the containing object’s children collection.As for a shared class, I believe from the the MSDN that they do not share a base class other than
Objectso you’ll have to stick with that or wrap them with your own containing class.EDIT: Here’s a more fully fleshed out way handling it with wrapping interfaces and factories.
First, define an interface with a shared based type (in this case
object) with which you can pass around the images:Then a simple factory for the user API to wrap the images with and have compile-time safety as to which image types are strictly supported:
Then your displaying class or view can receive these
IImageWrapperobjects and convert them into usable types:Some sample usage:
As this is, the underlying type of the image isn’t too strongly enforced. If you wish, you can update the factory to return strongly typed
IImageWrapperobjects asPictureBoxImageWrapperand in turn have the display class strongly typed against those that it supports, but that kinda defeats the purpose (you may as well strongly type againstPictureBox/DataGridViewImageCellas in my first answer.EDIT: Yet another way is to leverage implicit operators for your “factory”. This way your API just “passes” in the raw image objects and if they’re supported, an implicit operator will be found. If they’re not, then you’ll get a compile time exception: