0

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?

1
  • 1
    You should take a look at LINQToCSV. Commented Feb 28, 2013 at 9:40

2 Answers 2

4

You can use the Convert.ChangeType method:

myObject.Field = Convert.ChangeType(value, fieldType);
Sign up to request clarification or add additional context in comments.

1 Comment

well I kind of missed this function, thank you for pointing in out
0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.