I’m absolute beginner in C# and object oriented languages in general so I find this tutorial on the web and stuck up at functions.
Now, it says:
you declare function like this:
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
but it does not say that this method has to be outside of Main() method.
And also, it says the function is called like this:
int result = AddNumbers(10, 5);
Console.WriteLine(result);
My guess is you HAVE TO put this code in Main() method, but it does not say you have to first make object so the correct code is:
Program add = new Program();
int result = add.AddNumbers(10, 5);
Console.WriteLine(result);
‘Program’ is the name of the parent class.
So I’m confused now. I’m not familiar with C# versions, but as my conclusion this tutorial is for C# 2.0.
Since this tutorial is on #2 for google “C# tutorial” my question for me and for the future learners is:
is this mistake or is this the way you did it in C# 2.0 or is it just written in a such way so it’s not clear enough for absolute beginners?
The tutorial you are using is misleading. In c# there is no free standing functions. All executable code is placed in methods which belong to classes.
This is why it is best to avoid the term ‘function’ and use what is commonly used – method (of a class).
Methods can be static – those are called on the class and do not need a class instance, or instance methods – those require an existing instance which will have to be created first