this is a conceptual question, but if i initialize a variable in c# as public wi
ID: 644852 • Letter: T
Question
this is a conceptual question, but if i initialize a variable in c# as public will it be able to be used in the class as I want a variable "player1" and a variable "player2" where either could be one of the two (or more)
Player
Computer
Here is what i would like to know how I would do:
public class Game
{
//equivalent of initializing it here
public bool islogging;
public string[] log;
public int draws, round;
public Game(player p1, computer p2)
{
public player player1 = p1;
public computer player2 = p2;
}
//other overloads here...
...
}
trying this it doesn't work as the public keyword is rejected
public Game(player p1, player p2 )
{
public player player1, player2;
player player3 = p1;
player player4 = p2;
}
Explanation / Answer
It's a fundamental matter of scope.
Variables declared within a function are bound to the lifespan and accessibility of that function.*
C# doesn't allow you to declare variables that will persist as part of the class from within a function.
*Lambda expression can sometimes invalidate that statement, but that's well outside the scope of what you're asking.
To accomplish what you're asking, use this syntax.
public class Game
{
//equivalent of initializing it here
public bool islogging;
public string[] log;
public int draws, round;
public player player1;
public computer player2
public Game(player p1, computer p2)
{
player1 = p1;
player2 = p2;
}
//other overloads here...
...
}
or you could also try the following. But keep in mind that player1 and player2's scope will end with the constructor function.
public class Game
{
//equivalent of initializing it here
public bool islogging;
public string[] log;
public int draws, round;
public player player1;
public computer player2
public Game(player p1, computer p2)
{
player player1 = p1;
computer player2 = p2;
}
//other overloads here...
...
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.