Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm really new to coding c# and have recently been trying to learn how to do methods, but every time I've tried making a method in C# in visual studio it comes up with the same error: an object reference is required for non-static field, method, or property.

Here is an example of the code I used to try (and fail) to create a method (As I stated, this is in C# in Visual Studio):

C#
using System;

namespace metTestNov
{
    class Program
    {

        static void Main(string[] args)
        {
            int x = 2;
            int xReturnTest = Program.returnNum(x);
        }
        public int returnNum (int x)
        {
            return x;
        }

    }
}


What I have tried:

I've tried changing 'public' to 'private', I've tried putting the method before the 'main' method.
Posted
Updated 5-Nov-21 7:59am
Comments
[no name] 5-Nov-21 13:57pm    
In the present context, returnNum must be defined as "static". The "Main" entry point is a static method; it has no "object instance" associated with it; which you would need to call retrunNum otherwise (an object instance of "Program").

1 solution

You have declared returnNum as a non-static method, but you are trying to call it as if it is static. So change your code in one of the following ways:
C#
public static int returnNum (int x) // make it static


C#
Program prog = new Program(); // create an instance of the Program class
int xReturnTest = prog.returnNum(x); // call returnNum on the instance object

But what you should really do is get a good tutorial on C# and learn it in a structured fashion. .NET Book Zero by Charles Petzold[^] is an excellent starter.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900