+ 1

I didn't understand contructors some one please explain

30th Jan 2018, 11:25 AM
Saitharun Burra
2 Answers
+ 2
you need to think about constructors every time you create an object of a class , because the constructor is a method and it is a member of the class , it helps you get control and set up the contents of the new object. in c# every single class must have a constructor method , so if you declare the constructor method or not in the class ,the c# compiler creates a default one for you public class Account { public Account() { // this is the default constructor } }//notice the constructor is public and has the same name as the class's name it is public so that it can be accessed from external classes the default constructor has no parameters but you can make your own constructor method and feed it with the information you want class Person { private int age; private string name; public Person(string nm) {//this is a custom constructor and takes a string parameter (nm) and then //assign it to the name property name = nm; } public string getName() // by using this method we can output the name //because name is a property and it is private " this is known as encapsulation " { return name; } } static void Main(string[] args) { Person p = new Person("David"); // here an object is created , we feed the constructor with an input string "David" Console.WriteLine(p.getName()); // we get the output using the getName() method } //Outputs "David" hope this helps
30th Jan 2018, 12:06 PM
Rima
0
When an instance of a class is created, the class constructor is run before anything else. It's handy for initialising variables.
30th Jan 2018, 11:45 AM
Bagshot
Bagshot - avatar