InterviewSolution
| 1. |
Are C# Constructors The Same As C++ Constructors? |
|
Answer» Very similar, but there are some significant DIFFERENCES. First, C# SUPPORTS constructor chaining. This means one constructor can call another: Another difference is that virtual method calls within a constructor are routed to the most derived implementation - SEE Can I Call a virtual method from a constructor. Error handling is also somewhat different. If an exception occurs during construction of a C# object, the destuctor (finalizer) will still be called. This is unlike C++ where the destructor is not called if construction is not completed. (Thanks to Jon Jagger for pointing this out.) Finally, C# has STATIC CONSTRUCTORS. The static constructor for a class runs before the first instance of the class is created. Also note that (like C++) some C# developers prefer the factory method pattern over constructors. See Brad Wilson's article. Very similar, but there are some significant differences. First, C# supports constructor chaining. This means one constructor can call another: Another difference is that virtual method calls within a constructor are routed to the most derived implementation - see Can I Call a virtual method from a constructor. Error handling is also somewhat different. If an exception occurs during construction of a C# object, the destuctor (finalizer) will still be called. This is unlike C++ where the destructor is not called if construction is not completed. (Thanks to Jon Jagger for pointing this out.) Finally, C# has static constructors. The static constructor for a class runs before the first instance of the class is created. Also note that (like C++) some C# developers prefer the factory method pattern over constructors. See Brad Wilson's article. |
|