This is a really simple question that has always bothered me because almost everytime I write the code I am tripped up but this line.
Bitmap image = Bitmap.FromFile("c:\img.jpg");
I always intuitively assume that an object returned from a static method named FromFile
in class X
would be of type X
.
I realize that obviously I can cast back to Bitmap
if I want and I'm sure I'm missing something but as per the title why does Bitmap.FromFile(Path)
return an Image instead of a Bitmap
? Was this just a poorly thought out design or is there a more fundamental reason to return the parent class in this instance?
FromFile
is a static method on Image
, which is the base type of Bitmap
. You can access the static method through Bitmap, even though you are really calling Image.FromFile
. I suppose Bitmap could hide (or shadow) the FromFile on Image with its own that returned a Bitmap, but for whatever reason it wasn't done that way.
There are other child types of Image
, such as Metafile
(images with a .wmf extension). The purpose here is to achieve a polymorphic behavior - you can use FromFile to load an image and not care what underlying implementation is used to work with an image.