How does ConvertFromString work?

  • Thread starter Thread starter Sean Sampey
  • Start date Start date
S

Sean Sampey

I have two strings, strType and strValue. I am looking for a single,
generic function to create an object of type strType with a value of
strValue. I think I'm looking to use TypeConverter.ConvertFromString.
Perhaps I'm wrong. Using ConvertFromString (or any other function that'd
work), how do I acomplish this? Examples:

strType strValue
Integer 12
Boolean True
System.Drawing.Color #B5C7DE
System.Web.UI.WebControls.Orientation Vertical

Thanks!
Sean
 
I'm confused. You started out by saying that you "have two strings." That
implies that both strings are strings, and are therefore of the same type.
But then you say that you want to create an object of the first type with a
value of the second type. But since they are the same type, and they are
both strings, what exactly is the problem?

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.
 
Wait a second. I've been puzzling over your post, and I have a theory. Is it
possible that what you are asking is something along the lines of the
following?

Given data that is of a certain type and a certain value, you want to create
2 strings from the data, one of which holds the string representation of the
type, and the other of which holds the string representation of the value.

Is that what you're asking?

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.
 
Sorry for the unclear writing. What I am doing is serializing and
deserializing an object. To deserialize, I have the type of the new
object as a string (strType) and value it will hold as a string
(strValue). Using these two strings, I'm trying to create a new object
of type(strType) and value (strValue). For example, if strType were
"boolean" and strValue were "true", I would create a Boolean object
which equals True.
 
Hi Sean,

If your type is not a complex type, such as a class, you can use something
like the following:

string strType = "System.Int32";
string strValue = "567";
object o;
Type t = Type.GetType(strType);
TypeConverter tc = TypeDescriptor.GetConverter(t);
if (strValue.GetType().Equals(t)) o = strValue;
else o = tc.ConvertFromString(strValue);

Otherwise, you will have to deserialize it.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.
 

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

Back
Top