4
Answers

How to get Field-name and Field-value from an object ?

Ask a question
Sindhu Nair

Sindhu Nair

14y
5.5k
1
A big hello to all C# gurus :) .. am quite a novice in this, and am desperate to find some solution to my problem .. So please excuse me if this sounds too dumb .... and yes - any help is very much appreciated.

This is my class :

public class Product
{
    public string product_name;
    public string brand_name;
    public float width;
    public float height;
    public float depth;
    ....
    .... many more such fields
}

And I have filled my 'Product' instances with data and serialized them into individual xml files, and so I have around 1000 xml files. Now I need to fill my database (mySQL) with this data for each product.
In my product DB table, column names are exactly the same as the field names of my class.

I figured out that I can use MemberInfo.Name to get all the field names of my Product class. and I wish to programatically populate my DB with the values in the XMLs WITHOUT typing in the fieldnames individually.
I mean I DONOT want to write iProduct.product_name, iProduct.brand_name, etc. in the code to write to the DB, but would like to use MemberInfo.Name (or anything similar) to generate the field name dynamically.

If I have an object already populated with data, could someone please point me to how can I extract both the Field-name and Field-value from this object?

Many thanks for reading


Answers (4)