0

As I was learning ASP.NET on Youtube, an author created an instance of DBContext by creating private variable of type DBContext and initialize it to public constructor of a class:

public class CustomerController : Controller
{
    private ApplicationDbContext context;

    public CustomerController()
    {
       context = new ApplicationDbContext();
    }

}

So, my question is would it be the same if I just create private instance of DBContext, that is,

private ApplicationDbContext = new ApplicationDbContext();

Please can you explain why the author decided to create instance of DBContext as shown above and what is the benefit of it.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
Mir Usmanov
  • 31
  • 1
  • 4
  • Possible duplicate of [C# member variable initialization; best practice?](https://stackoverflow.com/questions/298183/c-sharp-member-variable-initialization-best-practice) – CodeCaster Jul 12 '18 at 07:37

1 Answers1

1

This is just a practice to follow, there is not any particular reason. My preference would be to initialize in the constructor if it's being changed from the constructor, otherwise assign on initialization.

Edit :

following are initializations are same :

private ApplicationDbContext context;

public CustomerController()
{
   context = new ApplicationDbContext();
}

AND

private ApplicationDbContext = new ApplicationDbContext();

But eventually, at some point, you will have your constructor overloaded as follows :

 public CustomerController(IService1 service1, IService2 service2)
    {
       // initialization here probably using DI
       // so it will looks consistant if you keep initialization at one place
       context = new ApplicationDbContext();
    }
Anupam Singh
  • 1,158
  • 13
  • 25
  • Hi Anupam, thank you for your reply, please could you clarify and give clearer explanation. Thank you for your undertanding and attention – Mir Usmanov Jul 12 '18 at 05:28