5

I trying to get some values from database by using entity framework

i have a doubt about

Difference between new ClassName and new ClassName() in entity framewrok query

Code 1

 dbContext.StatusTypes.Select(s => new StatusTypeModel() { StatusTypeId = 
 s.StatusTypeId, StatusTypeName = s.StatusTypeName }).ToList();

Code 2

dbContext.StatusTypes.Select(s => new StatusTypeModel { StatusTypeId =    
  s.StatusTypeId, StatusTypeName = s.StatusTypeName }).ToList();

You can see the changes from where i create a new StatusTypeModel and new StatusTypeModel() object.

  • The both queries are working for me. but i don't know the differences between of code 1 and code 2 .
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
  • 2
    http://stackoverflow.com/questions/3661025/why-are-c-sharp-3-0-object-initializer-constructor-parentheses-optional – jjj May 05 '15 at 06:50

1 Answers1

5

This has nothing to do with EF. This is a C# language feature. When you declare properties of a class using { ... } you don't need to tell that the empty constructor of a class shall be called. Example:

new StatusTypeModel() { StatusTypeId = s.StatusTypeId, ... }

is exactly the same like this:

new StatusTypeModel { StatusTypeId = s.StatusTypeId, ... }

There is no difference in performance. The generated IL (intermediate language) is identical.

However, if you don't declare properties you must call the constructor like this:

var x = new StatusTypeModel(); // brackets are mandatory
x.StatusTypeId = s.StatusTypeId;
...
Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62