0

if a class doesn't have a constructor how it can be instantiated in C#?

  • 6
    The magic word is default constructor which is always there, even if you don't see it. – Tim Schmelter Sep 22 '22 at 15:48
  • 3
    https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/instance-constructors#parameterless-constructors – canton7 Sep 22 '22 at 15:49
  • https://www.c-sharpcorner.com/article/constructors-in-C-Sharp/ here the author explained. Please go through this, you will get a clear picture – Amal Ps Sep 22 '22 at 17:24

3 Answers3

4

There's always a default, parmeterless constructor, even it it's not explicitly declared in the class (or struct). The only way to remove it, is to provide a different constructor.

So this:

class Foo
{

}

is the same as

class Foo
{
    Foo(){}
}

But this removes the default constructor:

class Foo
{
    Foo(string bah){}
}

If you provide a conctructor with parameters, the parameterless constructor is not added automatically anymore. You have to provide it yourself if needed. So with the last class definition you cannot write Foo f = new Foo(); anymore, because the parameter bah is mandatory.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

A default parameterless constructor is used if no explicit contructor is defined, all local members have their default values (they are not uninitialized like in C++)

cfaz
  • 185
  • 7
-1

The goal of the constructor is to instanciate the class with some attributes or properties defined on the constructor call. You can instanciate a class if it doesn't have any constructor overload, and it will by default not set any attributes. Then, every new instance will be identical.

Some attributes of the instance can be set by default in the class, and can be modified after the class is instanciated. you can also use the class to call methods.

You won't really see this much because it is considered bad practice, but you can still get away with it in a jank project.

BuyMyBeard
  • 66
  • 4