+ 2
Variable use
Hello. I'm trying to take input and display output using methods. Curently I'm confused when, were and how should I use variables properly. I understand that void is ussed then we don't return value to main, int then we return. But where are variable declaration is necessary? In main, In method, outside of methods? If someone could explain or give an example I would appriaciate.
3 Answers
+ 5
Sorry, I was saying a method call could be expensive. Not that it is (it depends on the complexity of the method). You can (and maybe even should) break long lines of code down into multiple methods for readability.
No x was not necessary. You could simplify Inp() to:
return Convert.ToInt32(Console.ReadLine());
I could not find y. But I assume you meant a.
a was never initialized in the method Out();
a in main and a in Out() are two different variables.
a in the main method would actually cause an error, since there was no variable named a that can be accessed within that scope.
Fix the main method by writing:
int x = inp();
Then you could say:
int a = x * 2;
Out(a);
Or, without variables:
Out(inp()* 2);
Passing the value to the method out:
public static void Out(int output){
// other code here
}
+ 5
Variable declarations are necessary whenever you need to hold on to the value the variable holds.
Generally, you should try to keep the variable in the smallest scope possible.
By scope, I mean block of code.
For Example,
for(;;;){
int someVar;
}
Here, you cannot access someVar outside the for loop. So, we would only want to declare it outside the for loop if we want to be able to access it outside the for loop.
You can also use a variable if you don't want to have to make multiple method calls.
For Example,
int a = myMethod();
if(a < 10 && a > 5)
Console.Write(a);
Instead of doing this:
if(myMethod() < 10 && myMethod > 5)
Console.Write(myMethod());
Maybe a call to myMethod() is expensive, so we used a variable to store the first value it returned.
+ 2
/* I understood your point that it is expensive to use methods and
* we should avoid it thenever possible, but I still can't resolve my
* problem. Can you have a look?*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
public static int Inp()
{
Console.WriteLine("Type a number: ");
/* Is int x necesary? */
int x = Convert.ToInt32(Console.ReadLine());
return x;
}
public static void Out()
{
/* Is int y necesary? */
int a;
Console.WriteLine("Your number times 2: " + a);
}
static void Main(string[] args)
{
Inp();
a = x*2;
Out(a);
}
}
}