3
I have a question and I would like to understand better how class instantiation works. More specifically the most appropriate way to do (if any) and the impacts of doing in the wrong way.
Assuming these two scenarios, which one should I use and why?
Scenario 1: Instantiating outside the methods.
public class PerfilController : Controller
{
PerfilDTO viewDTO = new PerfilDTO();
Perfil perfilNEG= new Perfil();
Recurso recursoNEG = new Recurso();
public ActionResult Cadastro()
{
viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
viewDTO.ListaRecursos = recursoNEG.ObterRecursos();
return View(viewDTO);
}
public ActionResult Listagem()
{
viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
viewDTO.ListaRecursos = recursoNEG.ObterRecursos();
return View(viewDTO);
}
}
Scenario 2: Instantiating within methods
public class PerfilController : Controller
{
public ActionResult Cadastro()
{
PerfilDTO viewDTO = new PerfilDTO();
Perfil perfilNEG= new Perfil();
Recurso recursoNEG = new Recurso();
viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
viewDTO.ListaRecursos = recursoNEG.ObterRecursos();
return View(viewDTO);
}
public ActionResult Listagem()
{
PerfilDTO viewDTO = new PerfilDTO();
Perfil perfilNEG= new Perfil();
Recurso recursoNEG = new Recurso();
viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
viewDTO.ListaRecursos = recursoNEG.ObterRecursos();
return View(viewDTO);
}
}
NOTE: If there is another way and better can also alert me.
If you declare property within the method, it only exists in the method. If it is outside, it belongs to the instance and is visible in all methods.
– bfavaretto
Yeah, I’d rather put it away, but since I don’t quite understand it, I was still afraid it might be bad somehow. There is no problem then to start out of the methods then?
– Joao Paulo
Look, I’m no expert on C#, but it would be nice to state the visibility of these properties (private, public, etc.). So without declaring should all be implicitly public.
– bfavaretto
Friend, I’m no expert either, but I recommend researching on "Lazy Initialization", or "Initialization on Demand", where you only create the object instance when you actually use it, and this standard also implements the "Singleton" standard. Perhaps the evening if no one has elaborated an answer on this I post one. But I recommend reading on this subject.
– Fernando Leal