We help IT Professionals succeed at work.

Storing string name in a class

jschmuff
jschmuff asked
on
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

Comment
Watch Question

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;

Explore More ContentExplore courses, solutions, and other research materials related to this topic.