Answer the question
In order to leave comments, you need to log in
How to use a constructor correctly?
A holistic question arose with colleagues, how to use the object constructor more correctly?
Option 1:
public class Circle
{
public Circle()
{
}
public void Draw()
{
//draw code
}
}
class Program
{
static void Main(string[] args)
{
var circle = new Circle();
circle.Draw();
}
}
public class Circle
{
public Circle()
{
this.Draw();
}
public void Draw()
{
//draw code
}
}
class Program
{
static void Main(string[] args)
{
var circle = new Circle();
}
}
Answer the question
In order to leave comments, you need to log in
The constructor should have one responsibility - to initialize the resources. He must not draw.
So option two is a no-brainer.
If you need to create and draw at the same time, create a static method for this that will create, draw and return an instance.
It is more correct to use it as required in a particular situation. If some code needs to be called always when creating an object, it makes more sense to put it in a constructor. If you pass a flag to the constructor that determines whether this or that method will be run internally, this is a signal that you need to either create specialized child classes or call the method after initializing the object by hand, where it is required.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question