views:

623

answers:

5

Hello, I am trying to extend the Bitmap class so that I can apply my own effects to an image. When I use this code:

namespace ImageEditor
{
    public class Effects : System.Drawing.Bitmap

    {
        public void toBlackAndWhite()
        {
            System.Drawing.Bitmap image = (Bitmap)this;
            AForge.Imaging.Filters.Grayscale filter = new AForge.Imaging.Filters.Grayscale();
            this = filter.Apply(this);
        }
    }
}

I get the following error:

'ImageEditor.Effects': cannot derive from sealed type 'System.Drawing.Bitmap'

So is there a way to get around this or is it simply not possible to extend the class?

Thanks.

A: 

A sealed class means that the author has explicitly dictated that no classes may inherit from it. There's really no way around it. If you're looking to add functions to the Bitmap class, you could look at extension methods.

Of course you could write a wrapper class or a utility class, but extension methods will give you the behavior most like inheriting from Bitmap.

Adam Robinson
+9  A: 

You can't derive from Bitmap because it's sealed.

If you want to add a method to the Bitmap class, write an extension method:

// Class containing our Bitmap extension methods.
public static class BitmapExtension
{
    public void ToBlackAndWhite(this Bitmap bitmap)
    {
        ...
    }
}

Then use it like this:

Bitmap bitmap = ...;
bitmap.ToBlackAndWhite();
Judah Himango
A: 

+1 for Judah's answer.

Also, consider returning a new bitmap with the filter applied rather than modifying the original. This will give your app more options in the long run (undo etc)

Tim Jarvis
A: 

The previous answers are good - extension methods apply nicely here. Also, my first thought was that inheritance isn't a great choice to begin with, since you're not really creating a different kind of bitmap (is-a relationship), you just want to package up some code to manipulate one. In other words there's no need to pass a bitmap-derived class to something, you can just pass the modified bitmap in place of the original.

If you really were intending to override some of Bitmap's methods with your own, I would look carefully again at what you're trying to accomplish - for something as complex as image manipulation you might be better served by supplying functionality alongside the original methods as opposed to superseding them.

David Pope
A: 

You can extend the BitmapSource class if you move to WPF and adding a toblackandwhite method would be easy - but the penalty is having to use WPF to read the bitmap in. See Custom BitmapSource

mikej