I am trying to access the member variable Name, which I set it as a private member variable, to be displayed as an output. Please don't worry about why I set the member variable Name up as private. It's only for practice purposes.
Basically my output is to display a name on the shell. Either
My name is Sora
or
My name is Xehanort
Right now the code displays
My name is [BLANK]
I'd like to know the two ways of doing it. The first is via user input, and the second is when the name of the character is stored in the program variables. Now I know how to do it both ways but that is when my member variables are public, but not as private. I'd like to do it as private but I'm stumped.
These are my codes so far. The first one is the Character class...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp_Practice
{
class Character
{
private string Name;
private int Age;
private char Gender;
private float Height { get; set; }
private float Weight { get; set; }
private string Nationality { get; set; }
private string Appearance { get; set; }
//SET AND GET NAME
public void setName(string name)
{
this.Name = name;
}
public string getName()
{
return Name;
}
//SET AND GET AGE
public void setAge(int age)
{
this.Age = age;
}
public int getAge()
{
return Age;
}
}
}
...and the second one is the main program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp_Practice
{
class Program
{
static void Main(string[] args)
{
Character Hero = new Character();
Character Villain = new Character();
//List of Heroes
Hero.getName();
// Hero.Name = "Sora";
// Hero.Age = 19;
// Villain.Name = "Xehanort";
// Villain.Age = 79;
Console.WriteLine("My name is " + Hero.getName());
}
}
}
Please let me know how I can do this, or if it's not possible, let me know why also. I appreciate it.
If you have a string
value with a name you wish to set, you should be able to use Hero.setName(value)
rather than Hero.Name = value
.
This applies to both console input AND hardcoded variables.