frenchie
frenchie

Reputation: 51927

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 have 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.

Upvotes: 2

Views: 111

Answers (3)

ChaosPandion
ChaosPandion

Reputation: 78262

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
};

Upvotes: 2

JaredPar
JaredPar

Reputation: 754595

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.

Upvotes: 2

Femaref
Femaref

Reputation: 61437

There is no difference. If the type has a parameterless constructor, you can leave the braces out.

Upvotes: 0

Related Questions