Reputation: 13571
Which of the following is the best way to implement a poco?
Option 1:
public class PocoOption1
{
public PocoOption1(int val1,string val2)
{
Val1=val1; Val2=val2;
}
public int Val1{get;private set;}
public int Val2{get;private set;}
}
Option 2:
public class PocoOption2
{
public int Val1{get;set;}
public int Val2{get;set;}
}
What are the potential pro-cons of each approach?? Does it matter? Some people say that a DTO should be set only once. Is it a rule or just an opinion??
Upvotes: 3
Views: 1804
Reputation: 74270
With the new C# syntax where you can do things like:
Customer customer = new Customer{ Id = 1,
Name="Dave",
City = "Sarasota" };
you can safely use Option 2.
Please check here.
Upvotes: 3
Reputation: 10389
The options are slightly different. Option 1 allows you to set Val1, Val2 only once. Option 2 allows you to set and reset those values.
In general I am a fan of public default constructors. It makes the API more easily consumed. This is discussed in some detail by Krzysztof Cwalina and Brad Abrams in the Framework Design Guidelines book. Here are the highlights:
In my opinion, Option 2 is the way to go.
Upvotes: 3