0

Why does a constructor not cosist of a void?

class Person { private int age; public Person() <-----------why not public void Person() { Console.WriteLine("Hi there"); } } I have learned that a void function is not returning any value.

8th Dec 2018, 8:00 PM
Mike Willems
Mike Willems - avatar
3 odpowiedzi
+ 6
Constructors are the code that is used to create objects. Constructors start with the short name of the class, followed by parentheses, that contain any parameters, and then an opening curly brace and a closing curly brace. In between the curly braces you assign values to instance variables and call any methods that need to be called when an object of this class type is created. Constructors may look like methods, but they neither return a value nor do they have the tag 'void'. You can have as many constructors as you want in a class, but each constructor needs a unique set of parameters. If you don’t write a constructor for your class, the compiler will implicitly include a constructor that contains no parameters. Please note - a parameterless, empty constructor added implicitly by the compiler is called the default constructor. Strangely enough, the same parameterless, empty constructor explicitly written in code, is not called "default constructor".
8th Dec 2018, 9:33 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 4
Because they have a special syntax due to their uniqueness. Personally, it makes more sense to return this than void as that is what the caller receives so, if I designed the language, that would have been my syntax.
8th Dec 2018, 9:13 PM
John Wells
John Wells - avatar
0
thank you
12th Dec 2018, 8:30 AM
Mike Willems
Mike Willems - avatar