C# FAQ: Are constructors the same in Cplusplus and CSharp
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:FAQs |
| edit |
Are constructors the same in C++ and C#?
Although there are strong similarities between C# constructors and C++ constructors, there are, also, some significant differences.
Firstly, C# supports constructor chaining—one constructor can call another as in the following example:
class Employee { public Employee (string name, int salary) { ... } public Employee (string name) : this (salary, 0) {} public Employee() : this ("", 0) {} }
Secondly, virtual method calls within a constructor are directed to the most derived implementation.
Thirdly, error handling is a bit different. When an exception occurs during C# object construction, the destructor—finalizer—will be called. This behavior differs from C++ behavior in which the destructor is not called if construction is interrupted.
Lastly, C# has static constructors. A static constructor for a class executes before the first instance of the class is created.
Interestingly, some C# developers—like some C++ developers—prefer the factory pattern to constructors.
See also
- Are C# constructors inherited?
- How can one constructor call another?
- Are constructors the same in C++ and C#?
- Are destructors the same in C++ and C#?
- How call a virtual method from a constructor or destructor?
- How do destructors work in C#?
- How enforce constructor correctness in C#?
- How make a C# destructor virtual?
- What are the differences between C# and Java constructors?
- What are the differences between C# finalizers and Java destructors?
- What is the syntax for calling an overloaded constructor from within a constructor?
- Why must
structconstructors have at least one argument? - C# Design Patterns Made Simple