Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between new ClassName and new ClassName() in entity framewrok query [duplicate]

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 .
like image 782
Ramesh Rajendran Avatar asked May 05 '15 06:05

Ramesh Rajendran


1 Answers

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;
...
like image 96
Quality Catalyst Avatar answered Sep 29 '22 20:09

Quality Catalyst