Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
namespace CSharp_Accessors
{
    class Person
    {
        private string myName = "N/a";  // Private string, cannot be accessed directly:
        private int    myAge  = 0;       // Private Integer, cannot be accessed directly:

        public string Name
        {
            get { return myName; }     // This is an Accessor, is used to access private identifiers:
            set { myName = value; }     // In this case the private identifier is [myName]:
        }

        public int Age
        {
            get { return myAge; }      // This is an Accessor, is used to access private identifiers:
            set { myAge = value; }     // In this case the private identifier is [myAge]:
        }

        public override string ToString()                   //
        {                                                   // I dont understand how this is access or why this function is read without nay name given to it.
            return "Name = " + Name + ", Age = " + Age;     //
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Simple Properties");

            // Create a new Person object:
            Person Person = new Person();

            // Print out the name and the age associated with the person:
            Console.WriteLine("Person details - {0}", Person);

            // Set some values on the person object:
            Person.Name = "Joe Beef";
            Person.Age = 42;
            Console.WriteLine("Person details - {0}", Person);

            // Increment the Age property:
            Person.Age += 1;
            Console.WriteLine("Person details - {0}", Person);

            // Pause screen
            Console.ReadKey();
        }
    }
}


I dont understand how this block called when it doesnt have a name associated with it nor has it been called.

---
public override string ToString()                   //
        {                                                   // I dont understand how this is access or why this function is read without nay name given to it.
            return "Name = " + Name + ", Age = " + Age;     //
        }

---

I was reading the tutorial found at:

Properties or Accessors
Posted

1 solution

Console.WriteLine("Person details - {0}", Person); uses the ToString() method.
When you override this (as is done in your class), this overriden method is called.

If not, the default ToString method would have been called.

How To: Override the ToString Method [^] might give you some more insight into this issue.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900