0

What is meaning of "??" and why not return "(dbContext = new TeduShopDbContext())" instead of return dbContext ?? (dbContext = new TeduShopDbContext())

   public TeduShopDbContext Init()
{
    return dbContext ?? (dbContext = new TeduShopDbContext());
}

thank for helping

  • `??` means return the first value unless it's null, in which case return the next value. In this case `dbContext` is clearly defined outside the scope of this method and may already be initialized so it attempts to return that before returning a new instance.[See the documentation](https://msdn.microsoft.com/en-us/library/ms173224.aspx); – Equalsk Jan 19 '17 at 22:50

2 Answers2

1

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

See here more examples!

Moshe D
  • 768
  • 1
  • 4
  • 13
0

This is a slick little trick I use often. It's called a Null Coalescing Operator.

All it does is return dbContxt, unless dbContext is null, in which case, dbContext is initialized to a new instance of TeduShopDbContext, and that instance is returned.

This little trick lets you initialize properties on their first Get operation, or in this case, keeps the Init function from creating new instances if it's called multiple times.

Edit: Here is a more verbose approach that does the same thing:

public TeduShopDbContext Init()
{
   if(dbContext == null)
      dbContext = new TeduShopDbContext();

   return dbContext;
}
Wesley Long
  • 1,708
  • 10
  • 20