Type.GetFields change from 1.1 to 2.0

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have some code that worked fine with .NET 1.1 but something has changed in
2.0 that I don't see documented. I have the line:

foreach (FieldInfo field in type.GetFields())

But there are never any fields returned like there was with 1.1. With the
help if ildasm I tried the following and it returns some properties.

foreach (PropertyInfo property in type.GetProperties())

One other problem is that when I call GetMembers and look at each of the
MemberType it seems that none are FieldType anymore. Any ideas? Am I just
doing something wrong?

Kevin
 
Kevin Burton said:
I have some code that worked fine with .NET 1.1 but something has changed in
2.0 that I don't see documented. I have the line:

foreach (FieldInfo field in type.GetFields())

What is 'type' the type object for?
But there are never any fields returned like there was with 1.1. With the
help if ildasm I tried the following and it returns some properties.
One other problem is that when I call GetMembers and look at each of the
MemberType it seems that none are FieldType anymore. Any ideas? Am I just
doing something wrong?

Is it that your fields are non-public? GetFields() doesn't return
private fields. You need to use the GetFields(BindingFlags) overload,
and pass BindingFlags.NonPublic or'd with BindingFlags.Instance and/or
BindingFlags.Static to get private fields.

This code works fine:

---8<---
using System;
using System.Reflection;

class App
{
static int _staticField;
int _instanceField;

static void Main(string[] args)
{
foreach (FieldInfo f in typeof(App).GetFields(
BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.Static))
Console.WriteLine(f.Name);
}
}
--->8---

-- Barry
 
What class are you trying to reflect? It sounds like the class now has
properties instead of fields.

Cheers,

Greg Young
MVP - C#
 
Back
Top