I looked all over the internet for solutions to this but none of them work:
public static void Main (string[] args)
{
Console.Write ("What is your name: ");
string input = Console.ReadLine ();
sayHi ();
}
public static string sayHi() {
Console.WriteLine ("Hello {0}!", input);
}
I don't need an answer that will help me do this without a global variable, that's not what I'm looking for
When I execute this I get this error:
The name 'input' does not exist in the current context
I tried making one of the lines
public string input = Console.ReadLine ();
but I get
Unexpected symbol 'public'
I tried
static string input = Console.ReadLine ();
But I get
Unexpected symbol 'static'
This
public static string input = Console.ReadLine ();
gives me
Unexpected symbol 'public'
I don't want a solution that doesn't use global variables
You should declare the variable outside of the Main method in the class containing both functions:
private static string input;
public static void Main (string[] args)
{
Console.Write ("What is your name: ");
input = Console.ReadLine ();
sayHi ();
}
public static string sayHi() {
Console.WriteLine ("Hello {0}!", input);
}
In this case the scope of the input variable will be the containing class and you can access it from all methods within this class.
There is no such thing as global variables in C#. This will do the trick for you. You could also try the static class with static members solution to simulate something like global variables, but that still won't be a global variable.
Try this (you're using an attribute in the class in this solution, it will be "global" inside this class)
public class YourClass{
private static string _input;
public static void Main (string[] args)
{
Console.Write ("What is your name: ");
_input = Console.ReadLine ();
sayHi ();
}
public static string sayHi() {
Console.WriteLine ("Hello {0}!", _input);
}
}
You can use Static class
static class Global
{
private static string _gVariable1 = "";
public static string Variable1
{
get { return _gVariable1 ; }
set { _gVariable1 = value; }
}
}
And you can use it like
Global.Variable1 = "any string value"
Related
I am trying to raed the value of userInput variable in my parent class which is stored in my child class, but I can't reach it and I get many errors one after one after each try. Can you please help me?
This is apart of my code:
//Child class
class tictactoe
{
public void beginGame()
{
ConsoleKeyInfo gebruikerInvoer;
gebruikerInvoer = Console.ReadKey();
//Rest of code
}
}
//Parent class
namespace Quizz
{
class Program
{
public static void Main(string[] args)
{
tictactoe minigame1 = new tictactoe();
while (minigame1.gebruikerInvoer)
{
//Rest of code
}
}
}
}
This is the error I get
'tictactoe' does not contain a definition for 'gebruikerInvoer' and no accessible extension method 'gebruikerInvoer' accepting a first argument of type 'tictactoe' could be found (are you missing a using directive or an assembly reference?)
I think that I will need to make a method to call it from the parent, if so: what type should I give since the variable is a ConsoleKeyInfo that is later converted to string?
gebruikerInvoer.KeyChar.ToString()
As the comments have made apparent, you need to first make the variable visible to the outside world. Local variables are always hidden from other classes. So lets fix this first:
class tictactoe
{
public ConsoleKeyInfo gebruikerInvoer; //Make public and move owner to class not method
public void beginGame()
{
gebruikerInvoer = Console.ReadKey();
//Rest of code
}
}
//Parent class
namespace Quizz
{
class Program
{
public static void Main(string[] args)
{
tictactoe minigame1 = new tictactoe();
while (minigame1.gebruikerInvoer) //CS0029 ConsoleKeyInfo cannot be implicitly converted to type Bool
{
//Rest of code
}
}
}
}
Moving on from there you need to define a statement to test the variable's value in a way that can return a true or false statement to use a while loop. To fix that we can do something like this:
class tictactoe
{
public ConsoleKeyInfo gebruikerInvoer;
public void beginGame()
{
gebruikerInvoer = Console.ReadKey();
//Rest of code
}
}
//Parent class
namespace Quizz
{
class Program
{
public static void Main(string[] args)
{
tictactoe minigame1 = new tictactoe();
bool minigameRun = minigame1.gebruikerInvoer.KeyChar == 't'
? true : false; //Assign a true value if the user entered the letter 't', else false
while (minigameRun) //Runs rest of code while minigameRun is true
{
//Rest of code
}
}
}
}
Then to escape the while loop you can use return, break, or upon some condition change the local bool minigameRun to false. The bool is initially assigned in this code using the ?: operator. You can read more about its use here
In C# , in Visual Studio, using a Console Application, is there a way to make methods in a class and call them in main program using readline?
Aka, a way to choose which methods to open when the program is running.
Easiest way is a switch statement for <4 cases, and a Dictionary for 4 or more cases.
class Program
{
private static IDictionary<string, Action> MethodMappings = new Dictionary<string, Action> {
{"Method1", Method1},
{"Method2", Method2},
...
}
public static void Main(string[] args) {
var methodCall = Console.ReadLine();
if (!MethodMappings.ContainsKey(methodCall)) {
//unrecognized command
}
MethodMappings[methodCall].Invoke();
}
private static void Method1() { ... }
private static void Method2() { ... }
}
This is very much possible using Reflection. Here is sample code to help you out:
class Program
{
public static void Hello1()
{
Console.WriteLine("\nHello 1");
}
public static void Hello2()
{
Console.WriteLine("\nHello 2");
}
static void Main(string[] args)
{
while (true)
{
String method = Console.ReadLine();
Type methodType = typeof(Program);
MethodInfo voidMethodInfo = methodType.GetMethod(method);
voidMethodInfo.Invoke(method,null);
}
}
}
For more information you can visit here.
This is a Console Program
Scenario:
I have a many function in my c# code and is set to be Public and Private. And I have static int Main(string args[]) of course. In int Main i calling some function Public and Private and thats interupting the function when i debug that. It says if main was static so all function must be static, yet my code in function Public and Private must be have "that" function. If i change static int Main with my public int main, debug cant be done because int Main must be static.
First im saying i really sorry for giving a non-understable question
If that's so confusing understanding my scenario, see my Example Code Here
namespace Example
{
class Program
{
public class ClassInPublic
{
public int Num;
public string Sentence;
}
ClassInPublic DeclaringInstance = new ClassInPublic();
private void Foo()
{
DeclaringInstance.Num = 35;
DeclaringInstance.Sentence = "Hello World";
Console.Write("This Private Function! And Assign Variable Value From ClassInPublic Variable");
}
private void Foo2()
{
Console.Write("This Single Foo didnt have any Instance Class");
}
static int Main(string args[])
{
Foo();
}
}
}
That's my case
And with help from others i already build this
namespace Example
{
class Program
{
public static class ClassInPublic
{
public int Num;
public string Sentence;
}
ClassInPublic DeclaringInstance = new ClassInPublic();
private static void Foo()
{
DeclaringInstance.Num = 35;
DeclaringInstance.Sentence = "Hello World";
Console.Write("This Private Function! And Assign Variable Value From ClassInPublic Variable");
}
private static void Foo2()
{
Console.Write("This Single Foo didnt have any Instance Class");
}
public static int Main(string args[])
{
Foo();
}
}
}
Error sign is lower right now, the rest is the ClassInPublic
It says i cannot declare
cannot declare instance members in static class
May someone assist me to overcome this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Example
{
class Program
{
public void foo()
{
Console.WriteLine("This is foo in Class Program");
}
static void fooStatic()
{
Console.WriteLine("This is Static foo");
}
static void Main(string[] args)
{
Program fooInstance = new Program();
fooStatic();
fooInstance.foo();
}
}
}
Here is a small example. Static functions are one per class. When you make public or private function they exist for each instance.
Edit:
Here is what I think you are trying to do:
namespace Example
{
class Program
{
public class ClassInPublic
{
static public int Num;
static public string Sentence;
}
ClassInPublic DeclaringInstance = new ClassInPublic();
private static void Foo()
{
ClassInPublic.Num = 35;
ClassInPublic.Sentence = "Hello World";
Console.WriteLine("This Private Function! And Assign Variable Value From ClassInPublic Variable");
}
private static void Foo2()
{
Console.Write("This Single Foo didnt have any Instance Class\n");
}
public static int Main(string[] args)
{
Foo();
return 0;
}
}
}
I'm learning C# and i'm having problems with variable scope in my simple console program.
The program runs perfectly so far except I know I will encounter issues when trying to reference variables previously instantiated.
I have tried to change methods from static to non static and also applied public/private access but to no avail.
I just need a nudge in the right direction, hope someone can help!
The error message i'm getting is :
Error 1 An object reference is required for the non-static field, method, or property 'ConsoleApplication2.Program.game()'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Program
{
int numberToGuess;
int numberGuessed;
int triesRemaining;
public void game()
{
Console.WriteLine(" ==Welcome to Guess My Number== \n");
Console.WriteLine("Player 1: Please enter your number to guess between 1 and 20: \n");
numberToGuess = int.Parse(Console.ReadLine());
Console.WriteLine("Player 2, please enter your first guess, you have 7 tries: \n");
numberGuessed = int.Parse(Console.ReadLine());
if (numberGuessed == numberToGuess)
{
correct();
}
else
{
incorrect();
}
}
public void correct()
{
Console.WriteLine("Congratulations, the number was in fact " + numberToGuess);
}
public void incorrect()
{
}
static void Main(string[] args)
{
game();
}
}
}
instance members (those not marked with the static keyword) exist once per object instance. Every instance of an object gets its own copies of them.
static members, on the other hand, exist once for the entire class and are shared by all object instances.
So, If you've got a class:
class Foo
{
public static int Alpha { get ; set ; }
public int Bravo { get ; set ; }
}
No matter how many instances of your Foo class are created, there is only one instance of Alpha. Any instance method or property can access a static member directly.
Instance members, since they exist on a per-instance basic, require an object instance to reference them. If you add some methods to the Foo class:
public static int DoSomething()
{
return Alpha * 3 ;
}
is perfectly valid — the method is static and the member is static. Ditto for an instance method:
public int DoSomethingElse()
{
return Alpha * 3 ;
}
Something like this will fail:
public static int AndNowForSomethingCompletelyDifferent()
{
return Alpha * 3 + Bravo ;
}
Bravo can't be referenced here without a reference to an instance of Foo. This will work however:
public static int AndNowForSomethingCompletelyDifferent( Foo instance )
{
return Alpha * 3 + instance.Bravo ;
}
As will this:
public int AndNowForSomethingCompletelyDifferent()
{
return Alpha * 3 + Bravo ;
}
Since the method is non-static (an instance method), it has an implicit reference (this) to its instance of Foo. The above is exactly equivalent to
public int AndNowForSomethingCompletelyDifferent()
{
return Alpha * 3 + this.Bravo ;
}
In your case, you could instantiate the class Program in your Main() method:
public static void Main( string[] args )
{
Program p = new Program() ;
p.game() ;
return ;
}
Or you could mark your methods game(), correct() and incorrect() as static, just as the Main() method is marked.
Hope this helps!
static methods/fields belong to the user-defined type, not the instance.
For example, if you look at this piece of code:
public class MyClass
{
public static void Foo()
{
}
}
the Foo() method, is not accessed from an instance of MyClass. Since it is static, you access it from the user-defined type itself. Ex:
public class Program
{
static void Main(String[] args)
{
MyClass.Foo();
}
}
Since Main() is static, you can only reference static methods or variables inside it (this excludes methods referenced from local instance variables).
In your code, the method game() and the fields/methods being called/invoked by game are not static, therefore you would only be able to access it via an object instance. Of course, making game() and all the other fields/methods static would result in a working piece of code.
For more information on static types, look here: http://msdn.microsoft.com/en-us/library/98f28cdx.aspx
I have gone on to complete the methods and it seems to be working great!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Program
{
int numberToGuess;
int numberGuessed;
int triesRemaining = 7;
string playAgain;
string player1, player2;
public void game() //Initiates the game instance
{
Console.WriteLine(" ==Welcome to Guess My Number== \n");
Console.WriteLine(" Player 1, Please enter your name: \n");
player1 = Console.ReadLine();
Console.Clear();
Console.WriteLine(" ==Guess My Number== \n");
Console.WriteLine("Hello " + player1 + " : Please enter your number to guess between 1 and 20: \n");
numberToGuess = int.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(" ==Guess My Number== \n");
Console.WriteLine(" Player 2, Please enter your name: \n");
player2 = Console.ReadLine();
Console.Clear();
Console.WriteLine("Hello " + player2 + " please enter your first guess, you have 7 tries: \n");
numberGuessed = int.Parse(Console.ReadLine());
if (numberGuessed == numberToGuess)
{
Console.WriteLine("Congratulations, the number was in fact " + numberToGuess);
newGame();
}
else
{
incorrect();
}
}
public void incorrect() //Method for dealing with incorrect answers
{
for (int x = 0; x < 6; x++)
{
triesRemaining--;
Console.WriteLine("Incorrect, you have " + triesRemaining + " tries remaining \n");
Console.WriteLine(player2 + ", please enter your next guess: \n");
numberGuessed = int.Parse(Console.ReadLine());
if (numberGuessed == numberToGuess)
{
Console.WriteLine("Congratulations, the number was in fact " + numberToGuess);
newGame();
}
else {
//Do nothing
}
}
Console.WriteLine("You have used up all your tries! You have failed. The number was: " +numberToGuess + "\n");
newGame();
} //Method for dealing with incorrect answers
public void newGame() //Method that gives the user the option to start a new game instance
{
Console.WriteLine("Would you like to play again? Type yes or no: \n");
playAgain = Console.ReadLine();
playAgain = playAgain.ToLower();
if (playAgain == "yes")
{
Console.Clear();
game();
}
else if (playAgain == "y")
{
game();
}
else
{
//Do nothing
}
}
static void Main(string[] args)
{
new Program().game();
}
}
}
I am getting an error of "No overload takes 0 args" at the Start(); line in my main method. I do not know how to fix it, and I've searched around and couldn't find anything.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static void main(string[] args)
{
Start();
}
public static string Start(string move)
{
Console.Write("");
string gameType = Console.ReadLine();
if (gameType == "s")
{
Console.Write("");
begin:
Console.Write("\nEnter your move: ");
move = Console.ReadLine();
switch (move)
{
case "r":
Console.Write("s");
Console.ReadLine();
break;
case "s":
Console.Write("");
Console.ReadLine();
break;
case "f":
Console.Write("");
Console.ReadLine();
break;
default:
Console.Write("\nInvalid move, try again\n\n");
goto begin;
}
Console.ReadLine();
return move;
}
else
{
return move;
}
}
static string Genius(string genius, string move)
{
Console.Write(move);
return genius;
}
}
}
The method call to Start should should be
Start("Something");
Edit: as others have pointed out: there is no point in passing anything to Start(). The move value passed in is ignored and replaced by whatever is read from the console. Therefore I suggest simply removing the argument from the Start() method signature so it just reads
public static string Start()
Since you are reading the move from the console, remove the string move from the parameter definition of Start and move it inside as a local variable and it should be fine:
public static string Start()
{ string move;
...
And btw, your main should be Main - in c# the main should have a capital M!
I recommend you read some basics of C#.
Hint: this is your method call:
Start();
and this is the method's signature:
public static string Start(string move)
There is a mismatch between them...
Your Start(arg) should be like:
private static string Start()
{
string move = null;
...
}
The start method expects a string as a parameter:
Examples:
Start("r");
Start("s");
Start("f");
You should either pass an argument when Start() is called (as Anders suggested) or you should remove the argument from Start() and declare it as a local variable instead:
public static string Start()
{
string move = string.Empty;