Opposite of "ToString"

L

Larry Smith

Once you call "ToString()" for an object, how can you then convert the
string back to the original object (assuming you know its type of course)?
Also, why does "ToString()" produce one string and
"TypeConverter.ConvertToString()" produce yet another (e.g., for a
"System.Drawing.Size" object, the former method yields, say, "Width=5,
Height=40" and the latter yields "5, 40"). Thanks.
 
G

Greg Young

There is no generic way to convert from a ToString back to an object (for
some objects there are parse methods suc h as DateTime.Parse). If you have a
simple class "Foo" that you call ToString() on it will return
"YourNameSpace.Foo" which won't be very helpful in recreating the object as
it does not have all of the data required in order to recreate the object.
Serialization will work in both directions as it includes all of the
necesary information to recreate the object.

TypeConverter is different by design, it is there to allow for other
mechanisms to be put in place (like your example). It is also a more generic
than a ToString() as it can work with other types
http://msdn2.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx
explains a bit mroe and gives some examples.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
 
N

Nicholas Paldino [.NET/C# MVP]

Larry,

It should be noted that ToString is not required to output the
information which will allow you to reconstitute an instance from the
results.

The documentation only states:

Return Value
A String that represents the current Object.

There are no guarantees that it can actually be used to create a
specific object.
The reason that a TypeConverter produces a different string is because
its function is to convert one type to another, (strings included), with no
loss of information. From the documentation:

Provides a unified way of converting types of values to other types, as well
as for accessing standard values and subproperties.

This is different from a representation of the object.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top