odiseh
odiseh

Reputation: 26547

Which one is best: Setting state using a public property or an overloaded constructor that accepts a parameter?

Which one should you use when you want to set the state of a Windows Forms control:

  1. Setting a Windows Forms state using a public property?

  2. Setting a Windows Forms state using an overloaded constructor that accepts a parameter?

Upvotes: 1

Views: 89

Answers (3)

k3b
k3b

Reputation: 14755

I prefer this convention:

  • If the initial state is required by the object beeing constructed:
    • put it into the constructor.
  • If it is optional or there is a meanful defaut or the object can live without it:
    • donot put into the constructor.

This way you can see what is necessary to create the object.

Upvotes: 3

Cody Gray
Cody Gray

Reputation: 244903

They're exactly the same. Or at least they should be, according to the Framework Design Guidelines. So you can expect that any of the standard classes exposed by the .NET Framework behave this way.

Any constructor method that accepts a parameter corresponding to a property should do nothing more than set that property to the specified value.

Quoting from Framework Design Guidelines by Cwalina and Abrams:

Do use constructor parameters as shortcuts for setting main properties.

There should be no difference in semantics between using the empty constructor followed by some property sets, and using a constructor with multiple arguments. The following three code samples are equivalent:

//1
EventLog applicationLog = new EventLog();
applicationLog.MachineName = "BillingServer";
applicationLog.Log = "Application";

//2
EventLog applicationLog = new EventLog("Application");
applicationLog.MachineName = "BillingServer";

//3
EventLog applicationLog = new EventLog("Application", "BillingServer");

Similar guidelines concerning constructors are also available online from MSDN here.

Upvotes: 1

Kunal
Kunal

Reputation: 1943

IF I am creating my own class , and feel that certain properties are absolutely required for entire lifetime of an object, I will use constructor to set it for me. This way, it becomes less confusing for the ones who end up using my class.

For e,g I always prefer setting connection string in the connection string itself rather than explicitly setting property for it.

Also there is good link at MSDN on constructor design; http://msdn.microsoft.com/en-us/library/ms229060(v=VS.80).aspx

Upvotes: 0

Related Questions