Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 248
  • Last Modified:

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.

Thanks.
0
newbieweb
Asked:
newbieweb
1 Solution
 
käµfm³d 👽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
            Console.WriteLine(propertyValue.ToString());
            Console.ReadKey();
        }
    }

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

Open in new window

0
 
ddayx10Commented:
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)?
0
 
newbiewebAuthor Commented:
Thanks. All set with this since I ended up not using reflection (this time).
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now