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.
3 ответов
+ 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".
+ 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.
0
thank you