Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Using reflection to find constants

112 views
Skip to first unread message

Mark

unread,
Aug 12, 2005, 9:48:00 AM8/12/05
to
Is there a way using reflection to interrogate a .dll and identify all the
declared constants, as well as their initial values?

Thanks in advance.

Mark


Nicholas Paldino [.NET/C# MVP]

unread,
Aug 12, 2005, 10:02:52 AM8/12/05
to
Mark,

You should be able to get all of the static fields on a type, and then
cycle through them, checking the IsLiteral property on the FieldInfo
instance representing the field. If IsLiteral returns true, then it is a
constant. To get the value, you can just call GetValue on the FieldInfo
instance, passing null for the instance, and it should return the value of
the constant.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- m...@spam.guard.caspershouse.com


"Mark" <ma...@iamnotintospam.com> wrote in message
news:%23puP1R0...@TK2MSFTNGP15.phx.gbl...

Mattias Sjögren

unread,
Aug 12, 2005, 10:01:01 AM8/12/05
to
>Is there a way using reflection to interrogate a .dll and identify all the
>declared constants, as well as their initial values?

Yes.

- Load the assembly (Assembly.Load[From])
- Get all types (Assembly.GetTypes)
- Get all static fields in each type (Type.GetFields)
- Check if it's a const (FieldInfo.Attributes has Literal set)
- If so retrieve the value (FieldInfo.GetValue)

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.

0 new messages