Logo 
Search:

C# FAQ

Submit Interview FAQ
Home » Interview FAQ » C#RSS Feeds

Are C# constructors the same as C++ constructors?

  Shared By: Angie Bennett    Date: Sep 07    Category: C#    Views: 1105

Answer:

Very similar, but there are some significant differences. First, C# supports constructor chaining. This means one constructor can call another:

class Person
{
public Person( string name, int age ) { ... }
public Person( string name ) : this( name, 0 ) {}
public Person() : this( "", 0 ) {}
}
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.

Share: 
 

Didn't find what you were looking for? Find more on Are C# constructors the same as C++ constructors? Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: