A method can either return values or not. Methods that return values can be called functions. And we have methods that return nothing (void
).
Let’s look at the following function, Multiplicar(int x, int y)
.
public int Multiplicar(int x, int y)
{
return x * y;
}
What we can see is that this method is public, has a return of the type int
and receives two parameters, x
and y
, both of the type int
. What this method does is multiply the received parameters and return to the caller.
Let’s look at that context:
// ...
int resultado = 0;
resultado = Multiplicar(10, 20);
I created a variable of the integer type, which receives the value processed by the method Multiplicar(10, 20)
. At the end, the result value will be 200.
Note that nothing was printed on the screen or anything, what happened was just what was asked to be done: multiply two numbers and return to who called it, which was the variable resultado
.
You have a method, called GetValue()
. In your case, GetValue()
returns an integer (int
) and does not receive parameters, fine.
Let’s look at what GetValue()
ago:
Dictionary<int, int> teste = new Dictionary<int, int>
{
{ 1, 1 },
{ 2, 2 }
};
public int GetValue()
{
return teste[1];
}
It returns the dictionary value in key 1, nothing else. It will return an integer to whoever called the function.
Analyzing "who called" GetValue()
...
static void Main()
{
Class1 classe = new Class1();
classe.GetValue();
Console.ReadKey();
}
In this case, the value of GetValue()
is not being stored or used for anything. This value is returned but not used.
As in your case, you want to print on the screen, in console applications (which is your case), you can use the method WriteLine
, class Console
.
Console.Writeline(int): Saves the text representation (character string) of the specified integer, followed by the current line terminator for the standard output stream.
Swap in kids, save the value of the integer in text form (type String
) to the standard output stream, which is the Console.
static void Main()
{
Class1 classe = new Class1();
Console.WriteLine(classe.GetValue());
Console.ReadKey();
}
In the case, classe.GetValue()
will be evaluated and printed on the screen through the Console.WriteLine
.
Resuming, Console.WriteLine
is one of those methods that do not have a return, void
.
Must-read: instruction return
.
I don’t know if I understand what you want and what the problem is, what is the desired result? You say
Console.WriteLine()
, but there’s no one in the code.– Maniero