Functions

Reply Forum
Forum postSimon @ 2009-03-16 13:46:04
ReplyReply to
Hi,

I can't get my function to work. Here's the code...

static void Main(string[] args)
{
int answer = addNumbers(1, 5);
Console.WriteLine(answer);
Console.ReadLine();
}

public int addNumbers(int num1, int num2)
{
int result = num1 + num2;
return result;
}

The error is "An object reference is required for the nonstatic field, method or property ConsoleApllication1.Program.addNumbers(int,int)

It's probably something really simple!


Forum postWebmaster @ 2009-03-17 08:15:39
ReplyReply to
Hi Simon,

As the error message says, the problem is that you are trying to call a non-static method from a static method. Your Main() function is static (declared with the static keyword), but the addNumbers() method is not. For more information on static members, please have a look at the following chapter in the tutorial: Classes - Static members

Now, to fix this quickly, simply declare your addNumbers() method as static, like this:

public static int addNumbers(int num1, int num2) { ... }

Hope that helps :)


Forum postJose Antonio @ 2010-04-05 20:42:14
ReplyReply to
hello well i have a problem here, i need to creat a lot of functions for a class but my problem is that i cant quite understando how to call them they all use parameters and i cant manage to get a function to run, besides i dont know how to invoque it from the main and i dont know how to put the parameters inside the (), im really new to C# and im getting desperate because i've been working for five days on this program and functions dont help me, and they are a requisite so if somebody would be so kind on giving me a how-to really basic on functions i would certainly apreciate that thx.


Forum postJim @ 2010-06-13 17:13:16
ReplyReply to
thanks, I needed that











© net-tutorials.com 2006 - 2010