I trying to get some values from database by using entity framework
i have a doubt about
Difference between
new ClassName
andnew ClassName()
in entity framewrok query
dbContext.StatusTypes.Select(s => new StatusTypeModel() { StatusTypeId =
s.StatusTypeId, StatusTypeName = s.StatusTypeName }).ToList();
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 .
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;
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With