Home > front end >  Why creating Constructor when Default can do the all?
Why creating Constructor when Default can do the all?

Time:10-13

Hope you are fine. I started learning C# about 2 weeks ago.I’ve been watching videos since now. Now he is teaching Constructions . I don’t get it. When you can use all strings and all numerical values, why restricting them? I mean does it make things bad if you just let it to be default? I tried many ways but I couldn’t find my proper answer. Your reply is so much to me and I really like to know why?!

CodePudding user response:

There are many reasons why one might want to use a constructor, but they are optional and depend on what the developer wants to do.

  • Constructors can receive parameters and set values based on the passed values/objects. So you can have many different constructors setting up the object in different ways
  • Constructors can also include logic to determine how fields/properties should be set. If at all
  • Constructors can call other constructors of the same class
  • Constructors are needed if you are using dependency injection, or readonly fields/properties.
  • If you want to create copies of your class object, then constructors can be very useful way to do this. Especially deep copies.
  • You can also have a static constructor. It is invoked only once in the class and it is invoked during the creation of the first reference to a static member in the class.
  • Constructors can also be private. And you can have a mix of public and private constructors.
  • Constructors are useful in inheritance, to ensure that parent fields/properties are still set correctly no matter what the child does (the child can then change these of course
  • Sometimes it is as simple as if you are setting many default values, it can be easier to read if they are all in the same place where you can group them together can comment on them together

BTW: Even if you don't create a constructor, the compiler will create a default one for you.

So simply put, C# provides you with lots of different options. It is up to you to select the one which suits you best for this specific task & class.

CodePudding user response:

There are several topics you can explore that will show where it is necessary... Dependency injection and Private Readonly Properties for example.

It can also just be convenient

new Uri(pathNameString) will generate the Uri object you can put in an http request by just providing the string at instantiation.

  • Related