Problem with Reflction  
Author Message
sureshsundar007





PostPosted: .NET Base Class Library, Problem with Reflction Top

Hi all,

I dont understand why this code doesnt works.

class Program

{

static void Main(string[] args)

{

Employee emp = new Employee();

Type tp = emp.GetType();

foreach (FieldInfo fi in tp.GetFields(BindingFlags.Public | BindingFlags.NonPublic))

{

Console.WriteLine("Name= " + fi.Name + ",Value= " + fi.GetValue(emp));

}

Console.ReadLine();

}

}

class Employee

{

public string UserName;

private string Password;

public Employee()

{

UserName = "suresh";

Password = "suresh";

}

}

I just want to get these two values using reflection.But this statment FieldInfo fi in tp.GetFields(BindingFlags.Public | BindingFlags.NonPublic) is not fetching any FiledInfo at all.Even this statment FieldInfo fi in tp.GetFields(BindingFlags.Public) is also not fetching any FieldInfo's. I'm using .NET 2.0.

Please help.

Thanks,

Suresh.



.NET Development33  
 
 
Mattias Sjogren





PostPosted: .NET Base Class Library, Problem with Reflction Top

Try including BindingFlags.Instance as well.



 
 
sureshsundar007





PostPosted: .NET Base Class Library, Problem with Reflction Top

Thanks.It works.

But why it mandates BindingFlags.Instance

Suresh.


 
 
Mattias Sjogren





PostPosted: .NET Base Class Library, Problem with Reflction Top

Because you want instance members to be returned. In the same way, you have to specify BindingFlags.Static to return static members.