Groups | Blog | Home
all groups > dotnet framework > november 2007 >

dotnet framework : Get Const Name and Values with Reflection?



coconet
11/30/2007 4:03:56 PM

I am trying to enumerate all of the name/value info from a struct with
Reflection. It looks like this:



public struct MyStruct
{
public const string ValueOne = "something";
public const string ValueTwo = "somethingelse";
}

In another class, I would like to enumerate it into MemberInfo[] so I
can use the parts. How to do that in C# 2.0?

Thanks.

coconet
11/30/2007 5:32:58 PM

That is gold!

Thanks.

Morten Wennevik [C# MVP]
11/30/2007 9:44:51 PM
Hi Coconet

MemberInfo won't tell you much other than what kind of members are avail=
able. You would then need to obtain a MethodInfo, PropertyInfo or Field=
Info to get the actual values. In your case this code piece should list=
the string

MyStruct f =3D new MyStruct();
Type t =3D f.GetType();
FieldInfo[] fields =3D f.GetType().GetFields();

List<string> values =3D new List<string>();
foreach (FieldInfo fi in fields)
values.Add(fi.GetValue(fi).ToString());


On Fri, 30 Nov 2007 22:03:56 +0100, coconet <coconet@community.nospam> w=
rote:

[quoted text, click to view]



-- =

Happy coding!
AddThis Social Bookmark Button