-3

I've already checked similar questions like

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

An object reference is required for the nonstatic field, method, or property

an object reference is required for the nonstatic field method or property

I have the following code in a Window:

public partial class RegistrationWindow : Window
{
    ...
    ...

    public RegistrationWindow()
    {
        InitializeComponent();

        this.Loaded += Init;
    }

    private void Init(object sender, EventArgs e)
    {
        RegistrationFunctions.GotoStep(this, 1); // <-- here the error occurs
    }

}

and I have the following class:

public class RegistrationFunctions
{
    public void GotoStep(RegistrationWindow window, int step)
    {
         ...
         ...
    }
}

I'm not using any static class or method, but I'm still getting the following error:

An object reference is required for the non-static field, method, or property...

Why am I getting this error even when I don't have anything static ??

Community
  • 1
  • 1
mrid
  • 5,782
  • 5
  • 28
  • 71
  • The problem *is* that nothing is `static`. `RegistrationFunctions` and/or `GotoStep` have to be `static` – Camilo Terevinto Feb 20 '19 at 12:07
  • @CamiloTerevinto can you explain ? – mrid Feb 20 '19 at 12:08
  • @mrid: On what object reference are you calling the method `GotoStep()`? It's a non-static method and you're trying to call it as a static method. – David Feb 20 '19 at 12:09
  • 1
    You need an `Instance` of a `RegistrationFunctions` and call the `Method` from there. Something like `RegistrationFunctions rf = new RegistrationFunctions();` and `rf.GotoStep(this, 1);` – LittleBit Feb 20 '19 at 12:09
  • Stated another way, `RegistrationFunctions.GotoStep(...)` is how to call `GotoStep(...)` assuming it is a static method of it's parent class, but it is not a static method in `RegistrationFunctions` as you have it defined. – lurker Feb 20 '19 at 12:11

1 Answers1

3

Why am I getting this error even when I don't have anything static?

You're getting this error because you don't have anything static. You're trying to use a static method that you've defined as an instance method. Right here:

RegistrationFunctions.GotoStep(this, 1);

You're not invoking it from an instance, you're trying to statically invoke it from the class. You have two options:

You can make it static:

public static void GotoStep(RegistrationWindow window, int step)
{
     //...
}

or you can create an instance of your class and call the method on that instance:

var functions = new RegistrationFunctions();
functions.GotoStep(this, 1);

Which way is correct is really up to you as you define the semantics of your program and decide what makes sense to be static and what doesn't.

David
  • 208,112
  • 36
  • 198
  • 279