Why am I getting Form1? Extension method must be defined in non-equivalent static class?

Error 1 Extension method must be defined in non-equivalent static class

This is how the expression form1 is declared:

public partial class Form1 : Form

      

Then I declared some variable as static:

private static FileInfo newest;
private static Stream mymem;
private static Bitmap ConvertedBmp;
private static Stopwatch sw;

      

I am using these variables in the constructor form1:

ConvertedBmp = ConvertTo24(newest.FullName);
mymem = ToStream(ConvertedBmp, ImageFormat.Bmp);

      

ConvertTo24 method:

private static Bitmap ConvertTo24(string inputFileName)
        {
            sw = Stopwatch.StartNew();
            Bitmap bmpIn = (Bitmap)Bitmap.FromFile(inputFileName);
            Bitmap converted = new Bitmap(bmpIn.Width, bmpIn.Height, PixelFormat.Format24bppRgb);
            using (Graphics g = Graphics.FromImage(converted))
            {
                g.PageUnit = GraphicsUnit.Pixel;
                g.DrawImageUnscaled(bmpIn, 0, 0);
            }
            sw.Stop();
            return converted;
        }

      

And the ToStream method:

public Stream ToStream(this Image image, ImageFormat formaw)
        {
            var stream = new System.IO.MemoryStream();
            image.Save(stream, formaw);
            stream.Position = 0;
            return stream;
        }

      

If I change something to be not static, I get an error in the ToStream method: Error 1 Extension method must be static

I tried to do something static, getting an error in Form1 when the whole thing is not static, I get an error in ToStream, so it must be a static method.

+3


source to share


1 answer


Since you are using the this

keyword
as the first parameter in ToStream

:

public Stream ToStream(this Image image, ImageFormat formaw)

      

which is only allowed in extension methods. Delete it.

If you want to use it as an extension method (which doesn't seem to be the case), the method must be in a static class like this:



public static class MyDrawingExtensions
{
    public static Stream ToStream(this Image image, ImageFormat formaw)
    {
        // ...
    }
}

      

Then you can call it (also) like this:

mymem = ConvertedBmp.ToStream(ImageFormat.Bmp);

      

+6


source







All Articles