When writing a method that takes a string and populates a poco based on it, is it better to have a static Parse(string s)
method like Int32.Parse()
or overload the constructor so it takes a string?
I prefer the constructor version, but including both is easy, since the constructor can just call Parse
. This is the pattern followed by the Guid
struct (and likely others as well.)
I should add that if you're not dealing with a struct
, then the static
method should probably be referring to the constructor (or even a separate method that both can call) since you can't assign to this
in a class
constructor.
EDIT: As TrueWill points out, if you do include Parse
, you should include TryParse
as well. Incidentally, Guid
is once again instructive: the Parse
method actually uses TryParse
, and just throws an exception if TryParse
returns false
.
If the method might fail due to an invalid string, I'd lean towards Parse and include TryParse as per the TryParse pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With