Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC4, C# Create object instance

Where should I create an instance? which way is better and why?

1) In the constructor?

public class UserController : Controller
{
    private UnitOfWork unitofwork;

    public UserController(){
         unitofwork = new UnitofWork();
    }

    public ActionResult DoStuff(){
    ...

2) as a private class member?

public class UserController : Controller
{
    private UnitOfWork unitofwork = new UnitofWork();

    public ActionResult DoStuff(){
    ...
like image 268
Expert wanna be Avatar asked Nov 12 '22 07:11

Expert wanna be


1 Answers

It's personal preference, really. Some people prefer to initialize outside of the constructor simply because there's less of a chance of someone else coming along and adding a new member without initializing it, since there's an example right in front of them.

As a general rule, if the initialization of an object requires any logic or requires parameters, then I prefer to do it in the constructor. Whatever you choose, though, make sure to remain consistent.

EDIT: Note, initializing in the constructor also allows you make calls to non-static methods and properties

like image 147
valverij Avatar answered Nov 14 '22 22:11

valverij