Basic C# Program Involving functions not working - c#

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;
}
}
}

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?

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;
}

Related

How do I parse (using TryParse) a string in a method to a global int

I'm struggling to parse user input to a global integer
When I give the global scoreString a value after declaring it like this --- static string scoreString = "55"; --- it works
static string scoreString = "55";
static bool scoreBool = int.TryParse(scoreString, out score);
static int score;
static void Main(string[] args)
{
Console.WriteLine("====STUDENT AVERAGE CHECKER====");
AverageMaker();
if (scoreBool)
{
Console.WriteLine("Parsing good");
Console.WriteLine(score);
}
else
{
Console.WriteLine("Parsing fail");
Console.WriteLine(score);
}
Console.Read();
}
public static void AverageMaker()
{
Console.WriteLine("-----Enter score---");
scoreString = Console.ReadLine();
}
You are of parsing scoreString out side of Main() function. Parse it inside AverageMaker() function, after reading string from Console
something like,
public static void AverageMaker()
{
Console.WriteLine("-----Enter score---");
scoreString = Console.ReadLine();
scoreBool = int.TryParse(scoreString, out score); //This was missing
}
Remove new line character as result of readline : scoreString = scoreString.Replace("\r\n", string.Empty); and try to parse

Methods not working? [duplicate]

This question already has an answer here:
C# - Why is this variable not being changed after being put through a method [duplicate]
(1 answer)
Closed 5 years ago.
Here is the block of code that I am having a bit of trouble with:
using System;
namespace TestProgram {
class Test {
static void Main() {
int number = 10;
MultiplyByTen(number);
Console.WriteLine(number);
Console.ReadKey(true);
}
static public void MultiplyByTen(int num) {
num *= 10;
}
}
}
When I run this block of code, I got 10 as the output instead of 100. My question is: Why does this happen and how to solve it?
Thanks for the help.
The problem is that when the variable number enters into the method MultiplyByTen the value is copied and the variable you are modifying inside it's in fact the copy, so, the original was not changed.
Try this instead:
public static void MultiplyByTen(ref int num)
{
num *= 10;
}
But remember you will have to call it with the ref keyword as well.
static void Main()
{
int number = 10;
MultiplyByTen(ref number);//Notice the ref keyword here
Console.WriteLine(number);
Console.ReadKey(true);
}
I recommend you to also check this out: Passing Objects By Reference or Value in C#
You need to return the value back to the function also assign the returned value to the number.
static void Main()
{
int number = 10;
number = MultiplyByTen(number);
Console.WriteLine(number);
Console.ReadKey(true);
}
static public int MultiplyByTen(int num)
{
return num *= 10;
}
Using your implementation:
using System;
namespace TestProgram {
class Test {
static void Main() {
int number = 10;
//MultiplyByTen(number);
//Console.WriteLine(number);
Console.WriteLine(MultiplyByTen(number));
Console.ReadKey(true);
}
static public int MultiplyByTen(int num) {
return num *= 10;
}
}
}

Whats the difference between ref parameter and return value (methods)

I've been studying methods and i have stumbled across the "ref" method. However both codes seem to accomplish the same thing:
class Program
{
static void Main(string[] args)
{
int number;
number = 5;
Console.WriteLine("Before method number= {0}", number);
AddThree (ref number);
Console.WriteLine("After method number={0}", number);
Console.ReadLine();
}
private static void AddThree(ref int lol) //carbon copy....so int number= 5 here
{
lol = 3;
Console.WriteLine("inside method number={0}", lol);
}
}
}
class Program
{
static void Main(string[] args)
{
int number;
int print;
number = 5;
Console.WriteLine("Before method number= {0}", number);
print =AddThree(number);
Console.WriteLine("After method number={0}", print);
Console.ReadLine();
}
private static int AddThree(int lol) //carbon copy....so int number= 5 here
{
lol = 3;
Console.WriteLine("inside method number={0}", lol);
return lol;
}
}
}
--
Is there an advantage that ref parameter has over return value? personally i dont see a massive difference..
Is there an advantage that ref parameter has over return value? personally i don't see a massive difference.
Well typically, ref is used when there's already something else being returned - e.g. for int.TryParse (which uses out, but that's similar). C# only supports returning a single value, so if you want two outputs from a method you have options of:
out parameters
ref parameters
Returning a composite value (likely to be more common in C# 7 with ValueTuple)
But there are other differences - importantly, changes to the ref parameter are visible immediately in terms of changing the original variable. That's most simply demonstrated when you have two ref parameters aliasing the same variable:
using System;
class Test
{
static void Main()
{
int x = 0;
RefTwo(ref x, ref x);
}
static void RefTwo(ref int a, ref int b)
{
Console.WriteLine(a); // 0
b = 5;
Console.WriteLine(a); // 5!
}
}
Oh, and as a little oddity, if you want a partial method to "return" a value, you basically need a ref parameter as partial methods must be void.
I would generally avoid ref parameters unless there's a very clear benefit. They make the interaction more complicated, in my view.

Can't convert from void to bool compile error

I am having some trouble with visual studio, as it says it won't compile. I can't figure out what the problem is. it says something like it can't convert from void to bool, even though there is no 'bool'. Here is my code:
using System;
namespace ConsoleApplication14
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(myFunction(14));
}
public static void myFunction(int x)
{
return x + 2;
}
}
What is causing that compile error?
try this
class Program
{
static void Main(string[] args)
{
Console.WriteLine(myFunction(14));
}
public static int myFunction(int x)
{
return x + 2;
}
}
You are returning an Int. Void has no return type. To make this work you will need
public static int myFunction(int x)
{
return x + 2;
}
The type void indicates that a mamber does not return anything. So when your method is marked as such it should not return a value. However when you call Console.WriteLine you need a value to be printed to the console.
Furthermore your method should make a calculation and return something - in your case an int. So instead of defining your method as void let it return an int:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(myFunction(14));
}
public static int myFunction(int x)
{
return x + 2;
}
}
In your myfunction method your returning some int value but myfunction return type is void in your code. Plaese change void to int and the application will work.
namespace ConsoleApplication1
{
class Program
{
public static int myFunction(int x)
{
return x + 2;
}
static void Main(string[] args)
{
Console.WriteLine(myFunction(14));
Console.ReadLine();
}
}
}

Call value from a method inside Main() function

I am trying to call a value from a method called GetInputstring from inside Main() method, and proceed to the next steps.
I am stuck regards to how I could get the value myInt and move along.
myInt (where it has two * around) inside Main() is where it gets the errors.
static void Main(string[] args)
{
GetInputstring(**myInt**);
if (**myInt** <= 0)
{
Write1(**myInt**);
}
else
{
Write2(**myInt**);
}
Console.ReadKey();
}
public int GetInputstring(int myInt)
{
string myInput;
//int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
return myInt;
}
static void Write1(int myInt)
{
while (myInt <= 0)
{
Console.WriteLine("{0}", myInt++);
}
}
static void Write2(int myInt)
{
while (myInt >= 0)
{
Console.WriteLine("{0}", myInt--);
}
}
MyInt is your parameter(the value you pass to your method) and it's not initialized. Further you don't catch your return value (which should be myInt)
You also need to make your methods static in order to call them from a static method or you create an instance of the class and invoke the method on it
That's how you'll get what you want:
static void Main(string[] args)
{
int myInt = GetInputstring(); //MyInt gets set with your return value
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
}
public static int GetInputstring() //Deleted parameter because you don't need it.
{
string myInput;
//int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
int myInt = Int32.Parse(myInput);
return myInt;
}
You need to initialize your myInt variable and store it in the local or global scope. With this variable you will need to set it with the value you get from GetInputString() because you are not passing the int as a ref it will not be assigned in the method. You also need to make your methods static so they can be called from Main without creating an instance, Ex: public static int GetInputstring()
int myInt = 0;
myInt = GetInputstring(myInt);
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
Alternatively (And preferably), you could make GetInputString() assign the value because it dosen't need myInt to be passed as an parameter.
static void Main(string[] args)
{
int myInt = GetInputstring();
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
}
public static int GetInputstring()
{
Console.Write("Please enter a number: ");
string myInput = Console.ReadLine();
return Int32.Parse(myInput);
}

Categories

Resources