I need help with C# programming; I am new to it and I come from C background. I have a Console Application like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Add_Function
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
int c;
Console.WriteLine("Enter value of 'a':");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of 'b':");
b = Convert.ToInt32(Console.ReadLine());
//why can't I not use it this way?
c = Add(a, b);
Console.WriteLine("a + b = {0}", c);
}//END Main
public int Add(int x, int y)
{
int result = x + y;
return result;
}//END Add
}//END Program
}//END Add_Function
It gives me this error on the line that I call Add():
An object reference is required for the non-static field, method, or property ‘Add_Function.Program.Add(int, int)’
Can anyone please explain to me why I have this problem. Is this because the architecture of C# is different than C, and the way I call it is wrong? Thanks.
Note: in C# the term “function” is often replaced by the term “method”. For the sake of this question there is no difference, so I’ll just use the term “function”.
The other answers have already given you a quick way to fix your problem (just make
Addastaticfunction), but I’d like to explain why.C# has a fundamentally different design paradigm than C. That paradigm is called object-oriented programming (OOP). Explaining all the differences between OOP and functional programming is beyond the scope of this question, but here’s the short version as it applies to you.
Writing your program in C, you would have created a function that adds two numbers, and that function would exist independently and be callable from anywhere. In C# most functions don’t exist independently; instead, they exist in the context of an object. In your example code, only an instance (an object) of the class
Programknows how to performAdd. Said another way, you have to create an instance ofProgram, and then askProgramto perform anAddfor you.The solutions that people gave you, using the
statickeyword, route around that design. Using thestatickeyword is kind of like saying, “Hey, this function I’m defining doesn’t need any context/state, it can just be called.” Since yourAddfunction is very simple, this makes sense. As you start diving deeper into OOP, you’re going to find that your functions get more complicated and rely on knowing their state/context.My advice: Pick up an OOP book and get ready to switch your brain from functional programming to OOP programming. You’re in for a ride.