Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
VB
i learn c++ and i begin learn c#, i dont understand method
help me error


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace text1
{
    class Program
    {
        public int pt(int l, int r)
        {
            return l + r;
        }
        static void Main(string[] args)
        {
            float i;
            var c = 10;
            Console.WriteLine("Hello World");
            Console.ReadLine();
            for (i = 1; i <= 10; i++)
                {   Console.WriteLine("Hello World");
                    Console.WriteLine(c);
                    
                };
            string a, b;
            a = "vu anh";
            b = "dep trai";
            Console.WriteLine(a + " " + b);
            int j;
            j = pt(3, 4);
            Console.WriteLine(i);
            Console.Beep();
            Console.ReadLine();
        }
    }
}

C#
i get error "An object reference is required for the non-static field, method, or property 'text1.Program.method(int, int)'"
thank
Posted
Updated 27-May-23 12:03pm
Comments
ZurdoDev 21-Nov-13 12:11pm    
Where's the code that is causing this error?

An alternative to requiring that you create an instance of Program is that you make pt() itself a static method. Since pt() only operates on its parameters (i.e. it doesn't reference any instance members of its defining type) making it static is an appropriate choice.
 
Share this answer
 
Since Main is static, you cannot use the rest of the Program Class inside your static method.

Therefore you need an instance of the Program Class.
Change
C#
int j;        
j = pt(3, 4);


Into
C#
int j;
Program P = new Program();
j = P.pt(3, 4);


I would recommend writing the pt(int,int) method in another class though, but maybe thats just me.
 
Share this answer
 
Hi,

you are calling an instance method pt() from a static method (Main). To correct this error, either (i) declare a variable of type program and then call the method or (2) add 'static' to the declaration of method pt().

C#
// option 1
int j;
Program program = new Program(); // new line
j = program.pt(3, 4);            // replace this line "j = pt(3, 4);"

// option 2
public static int pt(int l, int r)
{
    return l + r;
}
 
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