System.Reflection and the internal access modifier

G

Guest

This code is contained in one source file in VS 2005 project:

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

namespace ReflectionTest
{
internal class x
{
internal x() { }
public int property_1 { get { return 1; } }
public int property_2 { get { return 2; } }
}
class Program
{
static void Main(string[] args)
{
try{
string s= "{0}={1}";
x x0 = new x();
Console.WriteLine(String.Format(s,"property_1",x0.property_1));
Console.WriteLine(String.Format(s,"property_2",x0.property_2));
Console.WriteLine("\nUsing Get Property");
Console.WriteLine(String.Format(s,
"property_1",
x0.GetType().GetProperty("property_1").GetValue(x0, null)));
Console.WriteLine(String.Format(s,
"property_2",
x0.GetType().GetProperty("property_2").GetValue(x0, null)));
Console.WriteLine("\nUsing Get Properties");
foreach (PropertyInfo pi in x0.GetType().GetProperties())
Console.WriteLine(String.Format(s, pi.Name, pi.GetValue(x0, null)));
}catch(Exception e){
Console.WriteLine(e.Message + e.StackTrace );
}
Console.ReadKey();
}
}
}

Produces the following output, as expected.
property_1=1
property_2=2

Using Get Property
property_1=1
property_2=2

Using Get Properties
property_1=1
property_2=2



Changing the access modifier to internal on x.property_1 causes an exception:
Object reference not set to an instance of an object.
On the statement:
Console.WriteLine(String.Format(s,
"property_1",
x0.GetType().GetProperty("property_1").GetValue(x0, null)));

The statements:
Console.WriteLine(String.Format(s,"property_1",x0.property_1));
Console.WriteLine(String.Format(s,"property_2",x0.property_2));
Still work as expected.

What's special about internal on x.propery_1?
Do I need to use one of the other forms of GetProperty?
 
M

martin marinov

Hello Brian,

You must use
x0.GetType().GetProperty("property_1", BindingFlags.NonPublic | BindingFlags.Instance)
instead of
x0.GetType().GetProperty("property_1")

the internal accessor cause the member to be not visible to outer of the
class calls.

Regards
Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top