linq syntax option
I'm writing a linq-to-sql query to populate a list of objects MyModel.
For the class definition of MyModel,I have:
public class MyModel{
public Var1 {get;set;}
....
}
In the query, I hav开发者_Python百科e the option of writing both syntax:
var Query1 = from ....
where ....
select new MyModel
{ ... }
var Query2 = from ....
where ....
select new MyModel()
{ ... }
Both options work. What's the difference in adding the () in the select statement?
Thanks.
There is 0 difference. The second version of the syntax exists to let you call a non-default constructor when creating the objects before the object initializer code runs. For example
select new MyModel(value1, value2)
{ ... }
This is useful in cases where a type doesn't have a parameterless constructor or their are certain values which can only be set via the constructor.
The difference is that you can use the optional syntax to call a public parameter-less constructor. Try running this code:
class Test
{
public int Prop { get; set; }
public Test(int prop)
{
Prop = prop;
}
private Test()
{
}
}
var t = new Test
{
Prop = 1
};
There is no difference. If the type has a parameterless constructor, you can leave the braces out.
精彩评论