Christian Elsner
Christian Elsner

Reputation: 123

Converting strings to Object types in runtime

I have a class, something simple like

class Example
{
    uint id;
    ushort value1;
    string value2;
    DateTime timestamp;
 }

I also have a csv, like:

id;value1;value2;timestamp
5;0x2313;whatever;2012-12-23-12:14:34,567
6;0x2A14;something;2012-12-24:13:14:15:167

I would like to create objects based on the CSV, however the real class is a lot bigger and prone to change, so I would like to use reflection. I have some code getting the names of Properties and finding the corresponding string. What I don't get is, how I can convert the string to whatever type the Property is. I have found some code samples how to CAST the values, but casting a string to short is not what looks like a solution.

Any ideas?

Upvotes: 0

Views: 19876

Answers (2)

Moha Dehghan
Moha Dehghan

Reputation: 18443

You can use the Convert.ChangeType method:

myObject.Field = Convert.ChangeType(value, fieldType);

Upvotes: 4

Matthew Watson
Matthew Watson

Reputation: 109567

You may want to look at the Convert class. If you know the type to which you want to convert the string, you can use that.

Or, you can use the type's Parse() or TryParse() methods.

For example, to convert a string to a short you can use Int16.TryParse()

Upvotes: 0

Related Questions