The blog has moved to a new address. The blog is now located at http://devintelligence.com

Wednesday, May 30, 2007

System.Reflection - FieldInfo class

A FieldInfo class provides detailed information about a single field of a class or an interface. The reflected field may be a static field or an instance field. The FieldInfoSpy example shows how to obtain the field information of a class including the access modifiers, type etc:

 

using System;
using System.Reflection;

namespace ConsoleApplication1
{
internal class FieldInfoSpy
{
private static void Main(string[] args)
{
Type type
= typeof (Car);

//query type
FieldInfo[] fieldInfos = type.GetFields(
//Specifies that instance members are to be included in the search.
BindingFlags.Instance |
//Specifies that non-public members are to be included in the search.
BindingFlags.NonPublic |
//Specifies that public members are to be included in the search.
BindingFlags.Public |
//Specifies that static members are to be included in the search.
BindingFlags.Static);


foreach (FieldInfo fieldInfo in fieldInfos)
{
Console.WriteLine(
"Name:{0},Type:{1},Public:{2},Static:{3},Readonly:{4}",
fieldInfo.Name,
fieldInfo.FieldType.FullName,
fieldInfo.IsPublic,
fieldInfo.IsStatic,
fieldInfo.IsInitOnly
);
}

Console.ReadLine();
}
}

internal class Car
{
public bool broken;
private static string vendor;
public readonly string owner;
private int age;
protected string name;
}
}

A sample of the output follows:

Name:broken,Type:System.Boolean,Public:True,Static:False,Readonly:False
Name:owner,Type:System.String,Public:True,Static:False,Readonly:True
Name:age,Type:System.Int32,Public:False,Static:False,Readonly:False
Name:name,Type:System.String,Public:False,Static:False,Readonly:False
Name:vendor,Type:System.String,Public:False,Static:True,Readonly:False

4 comments:

Anonymous said...

Hi,

I am finding this example as near to my requirement, Can you tell me if I can use "System.Reflection - FieldInfo class" to get information about the class members stored in another file.

I want my user to select the .cs file and I want to read the class members from it. Is this possible?

Regards
NBaua
n_baua@yahoo.com

Taras said...

No .You can use System.Reflection only with an assembly ( compiled code library )

Anonymous said...

Hi,

Ok, I am trying to create a validator for the cs file whihc would suggest the user if they have entered the field/member name in correct case (i.e. in Camel or Pascel etc), if not the user will be seeing the correct suggestions depending upon their scopr(i.e. public/private etc).

Is it possible to create an application like this?

Regrads,
NBaua


Regards
NBaua
n_baua@yahoo.com

Taras said...

From my point of view you'd better use the regular expressions for your project