Home > Blockchain >  What happens if a class doesn't have a constructor? in C#
What happens if a class doesn't have a constructor? in C#

Time:09-23

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

CodePudding user response:

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.

CodePudding user response:

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 )

CodePudding user response:

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.

  • Related