why no string.tryParse method?

  • Thread starter Thread starter steven
  • Start date Start date
S

steven

Hi

Anybody know why there's no TryParse method for a string type? I can
do the following when trying to convert an object to int:

object oTest = 1;
int iValue;
int.TryParse(oTest, iValue);

But there's no equivalent for string:

object oTest = 1;
string sValue;
string.TryParse(oTest, sValue); // method TryParse doesn't
exist so this won't compile //
 
No - the first argument has to be string, and the second argument has to
be passed "out":

string test = "1";
int value;
int.TryParse(test, out value);

Re string, it is assumed that in most case .ToString() will do the job -
alternatively, Convert.ToString(...), or string.Format(...).

Basically, converting something from it's natural form to a string is
pretty-well covered.

Marc
 
steven said:
Anybody know why there's no TryParse method for a string type? I can
do the following when trying to convert an object to int:

object oTest = 1;
int iValue;
int.TryParse(oTest, iValue);

But there's no equivalent for string:

object oTest = 1;
string sValue;
string.TryParse(oTest, sValue); // method TryParse doesn't
exist so this won't compile //

There's no String.Parse() either. That's because the method Parse, by
convention, _parses_ a string to produce a value of a different type. The
conventional definition of "parse" is that you parse strings, not integers.

To get a string representation of any .NET object/value, use its ToString()
method. At the very least, there's always Object.ToString(), and types such
as Int32 or DateTime usually define additional overloads that provide extra
formatting options. Also, if you want to convert a value of an unknown type
to string in a culture-invariant manner, use Convert.ToString().
 
Back
Top