0

Attempting to understand Constructors with parameters.

Would appreciate if someone could explain how this code is being read to output "David". Attempting to learn constructors w/ parameters. Thanks! using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { class Person { private int age; private string name; public Person(string nm) { name = nm; } public string getName() { return name; } } static void Main(string[] args) { Person p = new Person("David"); Console.WriteLine(p.getName()); } } }

14th Dec 2021, 1:45 AM
Ademir
1 Réponse
+ 1
A constructor is a method like any other, and can take and process parameters like any other too. The main difference is that it's called only when creating a new object, and right after it's created So you can use the constructor to populate object attributes. Sometimes, class attributes change too, but this is a different subject. In this case, the constructor for class Person sets object "name" attribute with the argument passed to it. Whenever one calls the accessor to read "name" attribute, the method (accessor) will return the name set. So, new Person("David") creates a Person object with attribute "name" set to "David". Then, calling "getName" on this specific object will return object.name, that is, "David".
14th Dec 2021, 2:42 AM
Emerson Prado
Emerson Prado - avatar