Welcome to EMC Consulting Blogs Sign in | Join | Help

Kalpesh Prajapati

Accessing Non-public member of Class in .NET Framework

Few days back I was looking into .NET Framework design. While playing with server controls I come across requirement where I need to invoke protected member of Object before doing some processing. I found one of the way to access non-public member of Class using reflection.

Here is sample working code

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Reflection
{
    public class A
    {
        private int m_nMember;
        public A()
        {
            m_nMember = 1;
        }
        protected int Member
        {
            get
            {
                return m_nMember;
            }
            set
            {
                m_nMember = value;
            }
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            A ObjectA = new A();
            Type type = typeof(A);
            PropertyInfo oPropertyInfo = type.GetProperty("Member", BindingFlags.Instance | //Specifies that instance members are to be included in the search.
                                                                    BindingFlags.NonPublic
                                                                );
            //Get Value of protected property
            Object propvalue = oPropertyInfo.GetValue(ObjectA, null);
            //Print value of property
            Console.WriteLine("Value of " + oPropertyInfo.Name + " = " + propvalue.ToString());

            //Set Value of protected property
            oPropertyInfo.SetValue(ObjectA, 2, null );

            //Again Get Value of protected property
            propvalue = oPropertyInfo.GetValue(ObjectA, null);

            //Print value of property
            Console.WriteLine("Value of " + oPropertyInfo.Name + " = " + propvalue.ToString());

            Console.ReadLine();
        }
    }
}

Published 04 May 2007 08:36 by kalpesh.prajapati
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server (Personal Edition), by Telligent Systems