Reputation: 11
I'm currently following along with this course and in lesson 05.1 we create a private variable that takes the created Player class as the data type(?).
using GameEngine;
using System.Windows.Forms;
namespace UserInterface
{
public partial class DragonlightRPG : Form
{
#region Member Variables
private Player _player;
#endregion Member Variables
#region Constructors
public DragonlightRPG()
{
InitializeComponent();
// Instantiate a new Player class.
_player = new Player();
// Assign value(s) to the player object properties.
_player.CurrentHealth = 100;
_player.Gold = 25;
_player.MaximumHealth = 100;
_player.PlayerExperience = 0;
_player.PlayerLevel = 1;
// Get the value(s) of the properties from the _player object, and
// assign them to the text property of the labels on the form.
lblExperience.Text = _player.PlayerExperience.ToString();
lblGold.Text = _player.Gold.ToString();
lblHitPoints.Text = _player.CurrentHealth.ToString();
lblLevel.Text = _player.PlayerLevel.ToString();
}
#endregion Constructors
}
}
If the private variable _player
has the Player class set as the data type on line 10, why do we then create a new instance of that class on line 21 and assign it to the already predefined variable _player? Is there any reason why it's done this way? Can I do something like; Player player = new Player();
while achieving the same result?
Upvotes: 0
Views: 466
Reputation: 10184
The difference here is in the declaration of a variable versus the instantiation of an object that will be assigned to that variable.
In the class definition, the first reference to _player simply establishes a declaration to a variable of the type 'Player' - it does not create an instance of a Player object:
private Player _player;
The 'DragonlightRPG()' method, conversely, does perform the instantiation of the object with the 'new Player();' call, assigning the created object to the _player private member:
_player = new Player();
The former establishes the variable, the latter creates the object to be held in the variable.
You could have instantiated the object earlier; however, the most general guidance would be to create an object immediately when it is needed, use it, then destroy it. Further, the specifics of any particular use case might dictate that a particular object be created only at certain times, or should be instantiated only when a particular method is called. Those kinds of decisions are often a matter of individual requirements.
Upvotes: 4