Difference between new ClassName and new ClassName () in frame framrok request

I am trying to get some values ​​from a database using an entity framework

I have doubts about

Difference between new ClassName and new ClassName() in entity framework request

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 with which I create a new StatusTypeModel and new StatusTypeModel() object.

  • Both requests work for me. but I do not know the differences between code 1 and code 2.
+5
source share
1 answer

This has nothing to do with EF. This is a C # language feature. When you declare class properties with { ... } , you do not need to indicate that an empty class constructor should be called. Example:

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

exactly the same:

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

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

However, if you do not declare properties, you must call the constructor as follows:

 var x = new StatusTypeModel(); // brackets are mandatory x.StatusTypeId = s.StatusTypeId; ... 
+5
source

All Articles