Creating list of objects

Which is better one to follow

1.Creating object every time passing values as a parameters to constructor and add to the list
or
2.Create it once i.e, default constructor
and assign values to properties and add it to the list

Questions by Namedm   answers by Namedm

Showing Answers 1 - 12 of 12 Answers

crazystar

  • Aug 7th, 2009
 

Supplying parameters to the constructor at the time of object creation to initialize the object fields wil incur lesser cost compared to initialising fields through properties.
Reason: Properties are nothing but 'get_' and 'set_'  METHODS and therefore incur the  method invocation cost wen called.

  Was this answer useful?  Yes

Properties are more effective when compared to field values intialized by constructors. Properties can be either read only property, write only property or read-write property. But this is not the case in field values. Also the Properties are strongly typed. They appear in the intellisense to choose from among the class elements. So Properties are useful by utility more than the field values intialized through constructors.

  Was this answer useful?  Yes

v_n_r

  • Dec 23rd, 2009
 

If the values are constant and known then, Create object once i.e, default constructor
and assign values to properties and add it to the list.

If the values are changing or the values are given at the time of execution then parameterised constructor is used.

so it depends on the values and methods how we use in the code.

  Was this answer useful?  Yes

chaugule_p

  • Jan 20th, 2010
 

It is a scenario based decision the architecture of the application should take.

Any parameters which are required for that object to perform minimal Operations, can be added to the default constructor. e.g. UserName is mandatory for the user registration for any website.

By any means, if you maintaing the age of the person, it should be calculated based on the date of Birth and age should be just ready only property of the class, to make sure, no one overwrites it.

In general scenarios, I prefer to use properties instead of constructor parameters, as the code is more readable.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions