Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

C# - Get value of property from an object dynamically

Posted on 2012-03-10
7
Medium Priority
?
391 Views
Last Modified: 2012-06-27
Hi

I have a class called "shipment" that contains a lot of properties, such as Address1, Address2, Address3, PostCode, OrderNumber etc etc etc. This object gets passed to a web service, it creates the orders, then it sends an email. However, I want to make the email dynamic. For instance: for customer A, I might want to show Address1 and Address2, Customer B might want to show OrderNumber and Post Code

What I want to do, is have a database table that is called, and then says which properties of the object need to go onto the email. I think I need to use reflection, but I don't really understand it

So, in the db table will be a value of shipment.Address1 and shipment.Address2 which will be pulled out as strings, that then needs converting to take the value of the actual shipment.Address1 and 2

Does this make sense ? Hopefully have explained myself ok !

Thanks in advance
0
Comment
Question by:seancurt
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 2000 total points
ID: 37705110
This example shows how to get both a public field and a public property:
    public class shipment
    {

        public string Address1;

        private string _Address2;
        public string Address2
        {
            get { return _Address2; }
            set { _Address2 = value;  }
        }

    }

Open in new window


            shipment s = new shipment();
            s.Address1 = "Hello";
            s.Address2 = "World";

            string field = "Address1";
            System.Reflection.FieldInfo fi = s.GetType().GetField(field, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
            if (fi != null)
            {
                string value = fi.GetValue(s).ToString();
                MessageBox.Show(field + " = " + value);
            }

            string propName = "Address2";
            System.Reflection.PropertyInfo pi = s.GetType().GetProperty(propName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
            if (pi != null)
            {
                string value = pi.GetValue(s, null).ToString();
                MessageBox.Show(propName + " = " + value);
            }

Open in new window

0
 

Author Comment

by:seancurt
ID: 37705583
perfect - thank you so much
0
 

Author Comment

by:seancurt
ID: 37707593
Hi

I need to develop this a little more (will open a new question if you wish)

I have used your code as follows:

                                string propName = field;
                                System.Reflection.PropertyInfo pi = order.Header.GetType().GetProperty(propName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                                if (pi != null)
                                {
                                    string value = pi.GetValue(order.Header, null).ToString();
                                    //Console.WriteLine(propName + " = " + value);
                                    strEmailLine += value + "~";
                                }

Open in new window



I have the code inside a loop:

            foreach (Order order1 in file.Orders)

and then using some code I used before, I tried

Type type = Type.GetType("order1.Header"); - but this resolves to null

If I tried and use the full path Integration.Types.Order then it works, but this won't relate specifically to the instance of ORder1 inside the loop

Does this make sense ?

Thanks
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 37707596
Are you trying to get the type of "order1", or "Header"?

At any rate, use GetType() against that specific member like this:

    Type type = order1.GetType();

or this:

    Type type = order1.Header.GetType();
0
 

Author Comment

by:seancurt
ID: 37710045
Hi

Am trying to get it for both. The problem is that I need to do it dynamically, so order1 or order1.Header will actually be a string value. If I do the below, type is null, which implies it can't find order1.Header when passed as a string

            foreach (Order order1 in file.Orders)
            {

                string propName = "SHIPMENT_ID";
                Type type = Type.GetType("Order1.Header");
                System.Reflection.PropertyInfo pi = type.GetType().GetProperty(propName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                if (pi != null)
                {
                    string value = pi.GetValue(order.Header, null).ToString();
                    Console.WriteLine(value);
                }


            }

Open in new window

0
 

Author Comment

by:seancurt
ID: 37710058
Hi

In the above example, where i have done Type.GetType("Order1.Header") - this is a mistake, it should be all lower case, and that still doesn't work

Scott
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 37710502
Is "Header" an actual TYPE (class/structure), or is it simply the name of a field/property?

I'm thinking the latter.  If this is the case then you'd have to PARSE your string to separate into the Type portion and the FIELD portion.  To get a type from a string, though, I think you'd need the entire FULLY QUALIFIED name like:

    Type T = Type.GetType("WindowsFormsApplication1.Order");

Afterwards, you'd use GetField() or GetProperty(), and pass them "Header" as I demonstrated earlier.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question