user4420637
user4420637

Reputation:

What does a default constructor means in C#?

Based on what I have read, a constructor can have two meanings:

In computer programming languages the term default constructor can refer to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors (e.g. in Java)

and

In other languages (e.g. in C++) it is a constructor that can be called without having to provide any arguments, irrespective of whether the constructor is auto-generated or used-defined

So in the context of C#, what does a default constructor means, does it mean a constructor that is auto-generated and its only job is to initialize the members to some default values?

Upvotes: 0

Views: 3010

Answers (6)

VMAtm
VMAtm

Reputation: 28356

Default constructor in C# is, by definition, a constructor with such signature:

Class()
{

}

No parameters are provided here, so the compiler can call this method without any doubts. If your class is providing some other constructors, the default one woudn't be generated by a compiler and you have to add it manually:

Class() : this(null)
{
}

Class(object data)
{

}

In default constructor you can define your logic for a class which is respresenting it's state, such as a private fields or outer components. The other purpose of the default constructors can be found in Dependency Injection containers, there it used for a default instantiation of the object you are mapping.

Upvotes: 5

JammoD
JammoD

Reputation: 429

A default constructor is parameterless and is provided when the class contains no instance constructor declarations.

Try MSDN

Upvotes: 0

BradleyDotNET
BradleyDotNET

Reputation: 61379

In C#, the default constructor and the parameterless constructor are effectively synonymous. ie:

public MyClass()
{
}

Note that like in C++, providing a parameterized constructor removes the "provided" default one. You can always add a default/parameterless definition though.

Upvotes: 2

Artak
Artak

Reputation: 2887

The default constructor in C# is an auto-generated constructor in case you haven't provided any. In that case the compiler will add the default public constructor which accepts no arguments. However, as soon as you'll define any constructor, the default constructor won't be available any more.

Upvotes: 2

Habib
Habib

Reputation: 223392

Default constructor is parameterless constructor.

See: 10.10.4 Default constructors

If a class contains no instance constructor declarations, a default instance constructor is automatically provided.

Upvotes: 0

scartag
scartag

Reputation: 17680

In C# the default constructor is an empty constructor (with no parameters) generated for you by the compiler when you don't define any constructors.

Upvotes: 6

Related Questions