0

I am a beginner in C# and was creating a program with functions but unfortunately am very confused how to return the value in the function to the main program.

I have researched for other similar questions but i cannot find the answer as it is very basic.

class Program
{
    public int answer = 0;
    public int column = 0;
    public int UserInput;


    static void Main(string[] args)
    {

        BinaryInput(int UserInput);
        Console.WriteLine(UserInput);
        
    }

    static int BinaryInput (ref int UserInput)
    {
        UserInput = int.Parse(Console.ReadLine());
        return UserInput;

    } 

}

}

2 Answers2

3

Using a return value and a ref parameter at the same time for the same thing is completely unnecessary.

Just choose a method like this:

static int GetBinaryInput()
{ 
  return int.Parse(Console.ReadLine());
}

static void Main(string[] args)
{
  int UserInput = GetBinaryInput();
  Console.WriteLine(UserInput);
}

Or like that, prefering out here:

static void GetBinaryInput(out int UserInput)
{ 
  UserInput = int.Parse(Console.ReadLine());
}

static void Main(string[] args)
{
  GetBinaryInput(out var UserInput);
  Console.WriteLine(UserInput);
}

Using ref:

static void GetBinaryInput(ref int UserInput)
{ 
  UserInput = int.Parse(Console.ReadLine());
}

static void Main(string[] args)
{
  int UserInput = 0;
  GetBinaryInput(ref UserInput);
  Console.WriteLine(UserInput);
}

The first is more conventional and clean for the case in question.

Using an instance variable UserInput accessible to all methods is useless too, because this is a parameter between methods interactions, otherwise it is this one that is useless.

Also prefer TryParse to control errors, else use exception handling.

How TryParse method works?

What's the difference between the 'ref' and 'out' keywords?

When to use in vs ref vs out

Best practice: ref parameter or return value?

Which is better, return value or out parameter?

0

if you're returning a value, you will need the correct type of variable to return it too, e.g:

static void Main(string[] args)
{
  int output = BinaryInput();
  Console.WriteLine(output);
}

static int BinaryInput()
{
  UserInput = int.Parse(Console.ReadLine());
  return UserInput;
}
Michael P
  • 1
  • 1