Object reference for non-static field in C #

I created a function in C # as:

public void input_fields(int init_xcor, int init_ycor, char init_pos, string input) { char curr_position = 'n'; foreach (char c in input) { if (c == 'm') { Move mv = new Move(); if (curr_position == 'e' || curr_position == 'w') { init_xcor = mv.Move_Step(curr_position, init_xcor, init_ycor); } else { init_ycor = mv.Move_Step(curr_position, init_xcor, init_ycor); } } } } 

and I call the function like:

 input_fields(init_xcor, init_ycor, init_pos, input); 

but when called, it gives an error:

An object reference is required for a non-static field, method or property "TestProject.Program.input_fields (intermediate, int, char, string) 'xxx \ TestProject \ Program.cs 23 17 TestProject

I do not want the function to be static, since I also need to do a unit test.

What should I do for this? ... Please help me.

+4
source share
4 answers

You need to instantiate a class containing this method in order to access the method.

You cannot just execute methods as you seem to be trying.

 MyClass myClass = new MyClass(); myClass.input_fields(init_xcor, init_ycor, init_pos, input); 

You can create methods as static so that you can access them without instantiating the object, however you still need to reference the class name.

 public static void input_fields(int init_xcor, int init_ycor, char init_pos, string input) 

and then

 MyClass.input_fields(init_xcor, init_ycor, init_pos, input); 
+7
source

You must call this method on the object of the class in which this method belongs. Therefore, if you have something like:

 public class MyClass { public void input_fields(int init_xcor, int init_ycor, char init_pos, string input) { ... } ... } 

You must do:

 MyClass myObject = new MyClass(); myObject.input_fields(init_xcor, init_ycor, init_pos, input); 
0
source

Since the function is not static , you need to instantiate the class to call the method, for example

 MyClass cl = new MyClass(); cl.input_fields(init_xcor, init_ycor, init_pos, input); 

otherwise mark the method as static as

 public static void input_fields.... 

and name it as MyClass.input_fields (init_xcor, init_ycor, init_pos, input);

0
source

From your mistake, it seems that you are calling your method from main () or some other static method in the static class of the program. Just declaring your method as static will solve the problem:

 public static void input_fields(int init_xcor, int init_ycor, char init_pos, string input) ... 

But this is a quick fix and probably not the best solution (unless you are simply prototyping or testing a function). If you plan to continue working on this code, your method should be transferred to a separate class (static or not.) The program class and its main () function are designated as the entry point to the application, and not the only place in your application logic.

0
source

All Articles