Answer the question
In order to leave comments, you need to log in
Where is the best place to instantiate a C# class?
Hello. In the method, you need to create an instance of the class and return it from the method. Tell me where it is better to create it, in a method or a class field.
So?
class Cars
{
public Engine CreateEngine()
{
Engine engine = new Engine();
return engine;
}
}
class Cars
{
Engine engine = new Engine();
public Engine CreateEngine()
{
return engine;
}
}
Answer the question
In order to leave comments, you need to log in
in your examples there is no difference where to create - because. there is different behavior.
in the first case, a new one will be created for the engine request each time, and in the second, the same one will be returned.
The first one is viable, unless the engine is accessed by any other method in the Car class.
In the second way, you get that the method is called CreateEngine, but it does not create it, but only returns it.
class Cars
{
private Engine _engine;
public Engine Engine => _engine; //если нужен доступ к Engine из другого класса
public void CreateEngine()
{
_engine = new Engine();
}
}
The machine does not create the engines, the factories create the engines.
But if we ignore the meaning and names, then both options can exist:
In the first option, we create a new object each time. For example, it can be a method for parsing strings and creating different objects based on these strings. Something like: Node ParseNode(string textNode);
In the second case, the object produced by the method is created when the class is created. In this case, we have something similar to the Singleton pattern. We have one object, the exploitation of which is resource-intensive (for example, it takes a long time to create, or requires a lot of memory, or requires a separate network connection), but in general, this object alone is enough for the rest of the code to work. We somehow create this object and then give the same object to everyone who needs it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question