I am using a C# console application, where in the Main method I write all my code, but outside the main method I made a function/method to call it in the Main method. The point is that I did some research, and found that you need to instantiate the main class to access methods/functions outside of Main, but what I want to know is why you need to instantiate the main class to access them. Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace consolaPrueba
{
class Program
{
Int64 numero(Int64 val1, Int64 val2)
{
Int64 resultado = 0;
resultado = val1 * val2;
return resultado;
}
static void Main(string[] args)
{
Program objeto = new Program();
Int64 result = objeto.numero(5,10);
Console.WriteLine(result);
}
}
}
My function/method is "number", and in the Main I make the instance to finally call it like this "object.number(parameter1, parameter2);".
It works fine, but I'm wondering what it does when making that instance, since I tried to call it without the instance like I normally do in other languages and it didn't work.
In your case you have to instantiate it because the function Int64 number(Int64 val1, Int64 val2) is defined as private by omitting its scope (neither protected , nor private nor public , nor static appears in front of the type of your Int64 function ) therefore it can only be called from an instance of the class that implements it. If what you want is to use it without instantiating it from what I could see inside the Main method, you just have to set it to static .
Class definitions (what is contained in
class Nombre {}
) are the blueprints for building an object, not the object itself.As an analogy, imagine that you have the plans of a van, can you use the plans to make a move? Honestly, I don't think so. You will need to build the van based on the blueprints and then use the van for the move:
Original Answer:
The main method is a static method, so it belongs to the Program class, so there is no need to create an instance to call it.
While the method you created is not static, so it needs an object to call it, so you have to create an instance, to have an object, to call its method.
If you have two objects of the same Program class, each one has its own number method, but both have THE SAME Main method since it is static.
Update:
After answering or before, the question was raised "But shouldn't the method be inaccessible since it is private?" to which perform the following test:
Which is a program that compiles and whose output is
50\n50\n
, since private methods can be called within the class in which they have been declared, it does not matter that the method that uses them is called from outside if the call to the private method is written in the same class in which the method was declared.