Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse method or overload the constructor [closed]

Tags:

c#

.net

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?

like image 913
kay.one Avatar asked Aug 11 '11 15:08

kay.one


2 Answers

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.

like image 103
dlev Avatar answered Oct 29 '22 09:10

dlev


If the method might fail due to an invalid string, I'd lean towards Parse and include TryParse as per the TryParse pattern.

like image 21
TrueWill Avatar answered Oct 29 '22 09:10

TrueWill