Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CS1106 Extension method must be defined in a non-generic static class

Tags:

c#

wpf

I've been working on a project in WPF C# and I'm trying to animate an image to move down. I have found the "MoveTo" function on the Internet and when I pasted it in the code the error occurred.

Public partial class Window1: Window
{
    public static int w = 1;

    public Window1()
    {
        InitializeComponent();

    }

    public void MoveTo(this Image target, double newY)
    {
        var top = Canvas.GetTop(target);
        TranslateTransform trans = new TranslateTransform();
        target.RenderTransform = trans;
        DoubleAnimation anim1 = new DoubleAnimation(top, newY - top, TimeSpan.FromSeconds(10));
        trans.BeginAnimation(TranslateTransform.XProperty, anim1);
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        MoveTo(image, 130);
    }
}

What I need to do to fix this?

like image 809
Gal Didi Avatar asked Jan 24 '17 10:01

Gal Didi


2 Answers

public void MoveTo(this Image target, double newY)

this on the first argument of a method definition indicates an extension method which, as the error message says, only makes sense on a non-generic static class. Your class isn't static.

This doesn't seem to be something that makes sense as an extension method, since it's acting on the instance in question, so remove the this.

like image 91
Jon Hanna Avatar answered Sep 21 '22 11:09

Jon Hanna


MoveTo is an extension method - it's just a syntactic sugar for a static function, so you can call

image.MoveTo(2.0)

instead of

SomeUtilityClass.MoveTo(image, 2.0)

However extension methods must be placed in a static class, so you cannot place it in your Window class. You can just omit "this" keyword in the declaration and use it like a static method or you need to move the method to a static class.

like image 22
Paweł Słowik Avatar answered Sep 18 '22 11:09

Paweł Słowik