Ferruccio
Ferruccio

Reputation: 100748

How do you access an object whose type is defined at run-time?

I am using FileHelpers to parse CSV files whose structure is unknown using the following code:

            string cd = string.Format(@"[DelimitedRecord(""{0}"")]
                                        public sealed class ImportClass {{
                                            [FieldQuoted('{1}')]
                                            public string[] Fields;
                                        }}", _delimiter, _quote);
            Type t = DelimitedClassBuilder.ClassFromString(cd);

            var engine = new FileHelperAsyncEngine(t);

            engine.BeginReadFile(filename);
            object record;
            while ((record = engine.ReadNext()) != null) {

            }

            engine.Close();

This seems to work just fine. When I step through it with the debugger, record is an object of type ImportClass and the Fields field is correctly filled with data from the file.

The problem I have is how do I actually extract that data? I cant cast record to an ImportClass since that type is not known at compile time. Do I really need to use reflection or is there a simpler way to do this?

Upvotes: 2

Views: 256

Answers (3)

Preet Sangha
Preet Sangha

Reputation: 65555

Honestly the simplest way I can think of would be use the IronPython. Construct the string of code and pass it a python engine. We replaced a tonne of reflection with the DLR and IronPython.

Or as you say, you can reflection.

Edit: To reflect comments: You only need to include the 2 iron python assemblies as references. It isn't that hard. Honestly. Its not about installing a boat load other stuff.

Upvotes: 1

Aaronaught
Aaronaught

Reputation: 122684

There's probably a clean way of doing this exposed by the library you're using. Nevertheless, here is a general answer using Reflection:

Type t = ...  // You already have this
PropertyInfo fieldsProperty = t.GetProperty("Fields",
    BindingFlags.Public | BindingFlags.Instance);
string[] fields = (string[])fieldsProperty.GetValue(record, null);

Edit:

This library appears to have methods that allow you to read the file into a DataTable instead, and this seems to be their recommended approach. The example shown on this page is:

DataTable dt = engine.ReadFileAsDT("test.txt"); 

This is probably simpler and faster than using Reflection.

Upvotes: 0

Adeel
Adeel

Reputation: 19238

declare class in your code. no need to use reflection here.

Upvotes: 0

Related Questions