Need to use Reflection to read a property

I know the name of the property as a string, as well as its return type. But I need to call that property and presume I need to use reflection a nd posssible InvokeMember to do so.

Please explain how to do this or what I actually need to do.

newbiewebSr. Software EngineerAsked:
Who is Participating?
käµfm³d 👽Connect With a Mentor Commented:
Here's a quick example:
using System;
using System.Reflection;

namespace _27419388
    class Program
        static void Main(string[] args)
            MyClass c = new MyClass() { AProperty = 99 };
            string propName = "AProperty";

            // Get the instance's Type
            Type myClassType = c.GetType();

            // Change the binding flags according to how the property is defined.
            //  Here, since AProperty is an instance property (i.e. not static),
            //  we pass BindingFlags.Instance. We also pass BindingFlags.Public
            //  since the property is a public property
            PropertyInfo propInfo = myClassType.GetProperty(propName, BindingFlags.Instance | BindingFlags.Public);

            // Get the value stored in the property
            object propertyValue = propInfo.GetValue(c, null);

            // The value is returned as type object (see above),
            //  so we call the default ToString method to print it

    public class MyClass
        public int AProperty { get; set; }

Open in new window

Well since you mention property and reflection I am guessing you want to read the property of a page or a usercontrol otherwise I can't imagine what your involved in exactly.

What type of object are you trying to read a property from (class, page, uc, etc)?
newbiewebSr. Software EngineerAuthor Commented:
Thanks. All set with this since I ended up not using reflection (this time).
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.