Miha Markic [MVP C#] wrote:
Hi John,
If data is required at construction time then pass it through constructor.
Otherwise if number of property values isn't known, use properties or some
method which has all required arguments.
The problem with constructor is that you'll have to recreate all of them if
you decide to inherit from base class (and you want all of them).
--
Miha Markic [MVP C#, INETA Country Leader for Slovenia]
RightHand .NET consulting & development www.rthand.com
Blog: http://cs.rthand.com/blogs/blog_with_righthand/
"John F" <jf@rt.comwrote in message
news:19**********************************@microsof t.com...
Hello All,
Is it better to pass 'data' into a class object through a constructor and
then set it as a property internally in that object or is it ok to
instantiate a class object with no parameters and then attach 'data' to
the
class object by merely setting a property?
The ultimate goal is to have a bunch of objects all containing say a
patient
account number (the class does other things, but for sake of argument, the
data component is just patient account) set into a property for later
retrieval.
Thanks,
John
One reason to use a constructor would be if you want to create an
object but don't want to keep the variable. For example you may want
to add new objects directly to a list:
Dim ListOfObjects As New List(Of SomeClass)
ListOfObjects.Add(New SomeClass("something"))
Or perhaps a method needs to return a new instance of the class based
on parameters:
Public Function CreateAnObject(someString As String, someInteger As
Integer)
Dim something As String
'Do some calculation with the integer or some manipulation of the
string
something = <result of manipulation>
Return New SomeClass(something)
End Function
These are very simplistic examples, but using a constructor can make
the instantiating code easier to read.
In reality, what Miha wrote is correct. If the data is needed to
construct the object then use a constructor. Otherwise, it is entirely
appropriate to instantiate the object and then set the properties
later. Sometimes, you don't know what the properties should be set to
at the time of instantiation so setting the properties later is the
only option.