5

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(){
    ...
1
  • 1
    both the snippets would compile down to the exact same code imo. Commented Apr 10, 2013 at 16:21

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Depending on what you want to achieve. If you do it using a field, it will be initialized before the constructor, so you can do other things later.

In this particular example, it would be no much difference (other than the sequence).

Comments

0

I prefer to keep it in the constructor, as it allows you to extend it down the line if need be without updating all the locations you called it from, and also keeps your calling code cleaner and more succinct.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.