Call value from a method inside Main() function - c#

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

Related

Basic C# Program Involving functions not working

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

Get ref to field value in C# [duplicate]

This question already has an answer here:
Get Reference to Field from Reflection [duplicate]
(1 answer)
Closed 2 years ago.
I need to get a reference to a field value in C# but I cant find any way to get an actual reference to the field that can be passed as a parameter. Any help will be greatly appreciated.
Example:
public class SomeClass
{
public int value = 0;
}
public class SomeOtherClass
{
static void Main(string[] args)
{
SomeClass x = new SomeClass();
Console.WriteLine(x.value); //Outputs "0"
foreach (FieldInfo field in x.GetType().GetFields())
{
Log(ref field.value) //Outputs "10"
} // ^
} //Not a valid member
static void Log(ref int i)
{
i = 10;
Console.WriteLine(i);
}
}
Try the below
public class SomeClass
{
public int value = 0;
}
public class SomeOtherClass
{
public static void Main(string[] args)
{
SomeClass x = new SomeClass();
Console.WriteLine(x.value); // Output Line 1
foreach (FieldInfo field in x.GetType().GetFields())
{
Console.WriteLine(field.GetValue(x)); // Output Line 2
var y = (int)field.GetValue(x);
Log(ref y);
Console.WriteLine(y); // Output Line 4
}
}
static void Log(ref int i)
{
i = 10;
Console.WriteLine(i); // Output Line 3
}
}
Output:
0
0
10
10
class Program
{
public class SomeClass
{
public int value = 0;
}
public class SomeOtherClass
{
static void Main(string[] args)
{
var x = new SomeClass();
Console.WriteLine(x.value); //Outputs "0"
foreach (FieldInfo field in x.GetType().GetFields())
{
var value = (int)field.GetValue(x);
Log(ref x);
Console.WriteLine(x.value);
}
}
static void Log(ref SomeClass x)
{
x.value = 10;
}
}
}

What is the meaning of the static field in AttemptController in following sample code ?

I am newbie in C# and trying to learn static keyword. I don't understand why we need to initialize static field twice. as my understanding static field preserve the value during the program execution.
class Program
{
static void Main(string[] args)
{
AttemptController Obj = new AttemptController(3, 2);
Console.WriteLine("Maximum: {0}", AttemptController.MaxAttempts);
Console.WriteLine("Warning: {0}", AttemptController.WarningAttempts);
Console.WriteLine("Threshold: {0}", AttemptController.Threshold);
AttemptController Obj1 = new AttemptController(7, 5);
Console.WriteLine("Maximum: {0}", AttemptController.MaxAttempts);
Console.WriteLine("Warning: {0}", AttemptController.WarningAttempts);
Console.WriteLine("Threshold: {0}", AttemptController.Threshold);
Console.ReadLine();
}
class AttemptController
{
internal static int MaxAttempts;
internal static int WarningAttempts;
internal static int Threshold;
public AttemptController(int a, int b)
{
MaxAttempts = a;
WarningAttempts = b;
Threshold = MaxAttempts - WarningAttempts;
}
}
}
So a couple of proposed changes:
make the class static
get rid of the constructor as static classes cannot have instance constructors.
add a new method called init just for demo purposes.
using System;
namespace ConsoleApp4
{
internal class Program
{
private static void Main(string[] args)
{
AttemptController.Init(3, 2);
Console.WriteLine("Maximum: {0}", AttemptController.MaxAttempts);
Console.WriteLine("Warning: {0}", AttemptController.WarningAttempts);
Console.WriteLine("Threshold: {0}", AttemptController.Threshold);
AttemptController.Init(7, 5);
Console.WriteLine("Maximum: {0}", AttemptController.MaxAttempts);
Console.WriteLine("Warning: {0}", AttemptController.WarningAttempts);
Console.WriteLine("Threshold: {0}", AttemptController.Threshold);
Console.ReadLine();
}
}
public static class AttemptController
{
internal static int MaxAttempts;
internal static int WarningAttempts;
internal static int Threshold;
public static void Init(int a, int b)
{
MaxAttempts = MaxAttempts + a;
WarningAttempts = WarningAttempts + b;
Threshold = MaxAttempts - WarningAttempts;
}
}
}
Because you set MaxAttempts,WarningAttempts,Threshold fields in the constructor method.
When you use AttemptController Obj = new AttemptController(3, 2); it will set the value.
when you use will set MaxAttempts = 3 and WarningAttempts = 2
AttemptController Obj = new AttemptController(3, 2);
when you use will set MaxAttempts = 7 and WarningAttempts = 5
AttemptController Obj1 = new AttemptController(7, 5);
static fields let all instance use the same fields value.

Can't throwaway result of a val1 && val2?

I'm trying to do something like
public class Program
{
private static readonly Random r = new Random();
public static void Main()
{
RandomBool() && RandomBool();
}
private static bool RandomBool()
{
bool b = r.Next() % 2 == 0;
Console.WriteLine("Random bool value is {0}", b);
return b;
}
}
i.e. execute RandomBool() until it's false. (You can do this in JavaScript)
I guess I have to do
public static void Main()
{
bool throwAwayValue = RandomBool() && RandomBool();
}
Or is there a better way to do the same thing?
If you want to execute RandomBool repeatedly until it's false, can't you use while loop in your main?
while (RandomBool()) {
// wait
}
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/while

METHOD concept program in c# is not working

using System;
class Methodcalling
{
public int Values(int num1, int num2)
{
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
}
static void Main(string[] args)
{
int a, b;
Methodcalling m = new Methodcalling();
Console.WriteLine("enter a no.:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter a no.:");
b = Convert.ToInt32(Console.ReadLine());
int result = m.Values(a, b);
}
}
ERROR:'Methodcalling.Values(int, int)': not all code paths return a value
In this way its showing error in VISUAL STUDIO 2013.
This error is because you have declared the function to return an int, but your function does not return anything.
Have a look at this link here for a reference on the function declaration in c#.
For a relief from the error, try adding return 0; to the end of the function.
public int Values(int num1, int num2)
{
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
return 0; // Return zero to the calling function.
}
Now you could call this function like this to capture the return value.
int TheReturnValue = Values(num1 , num2); //You will get 0 as value for TheReturnValue variable.
or change the int to void as in public void Values(int num1, int num2) if you don't want to return any values.
here is the usage:
public void Values(int num1, int num2)
{
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
}
and you could call the function(void Return Type) like this:
m.Values(a, b); //without assigning it to a variable
Since you are only writing to console using this function, void datatype would be the better option.
I hope this helps.
You have to return an int value from the method as the method's signature defines a return type of int, and you are also calling
int result = m.Values(a, b);
which suggest that the method would return an integer but you have no return statement in your method.
You can modify the method like this if you don't want any integer to be returned.
using System;
class Methodcalling {
public void Values(int num1, int num2) {
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
}
static void Main(string[] args) {
int a, b;
Methodcalling m = new Methodcalling();
Console.WriteLine("enter a no.:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter a no.:");
b = Convert.ToInt32(Console.ReadLine());
m.Values(a, b);
}
}

Categories

Resources