Storing string name in a class

How do I store a string name in a class?

I thought it would look like the following code below but I dont know how to access the name in the class.



public class Character
    {
        string name;
 
        public string Name
        {
            get
            {
                return (this.name);
            }
            set
            {
                this.name = value;
            }
        }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            Character character = new Character();
 
            Console.Write("Character's Name: ");
            name = Console.ReadLine();
 
        }
    }
}

Open in new window

jschmuffAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
galar71Connect With a Mentor Commented:
You can write to the Name-variable in an instance of the Character class, the following way:

Instead of:

name = Console.ReadLine();

try...

character.Name = Console.ReadLine();

If you later want to refer to the same one, you should use myVar = character.Name;

Remember that the variables are case-sensitive, so name would not work in any case since you've named your property Name.

Also, to properly encapsulate the value, you should set the internal variable name to private, so it should be :

private string name;
0
All Courses

From novice to tech pro — start learning today.