Enumerating public constants from class

  • Thread starter Thread starter bz
  • Start date Start date
B

bz

Hi,

I have a class defined as below:
public class ColumnNames
{
public const string StockID = "StockID";
public const string LevId = "LevId";
public const string ProductieId = "ProductieId";
public const string PartijNummer = "PartijNummer";
public const string ArtNr = "ArtNr";
public const string Opslagplaats = "Opslagplaats";
public const string Geleverd_op = "Geleverd_op";
...

How can I enumerate all the public constants?

Thanks
 
Hi,

You can do that easily using reflection

Type type = typeof(ColumnNames);
FieldInfo[] fields = type.GetFields();
foreach (FieldInfo fi in fields)
Console.WriteLine(fi.Name + " = " + fi.GetValue(null));

If you need to filter on only public const fields use

FieldInfo[] fields = type.GetFields(BindingFlags.Static |
BindingFlags.Public);
 
Morten Wennevik said:
Hi,

You can do that easily using reflection

Type type = typeof(ColumnNames);
FieldInfo[] fields = type.GetFields();
foreach (FieldInfo fi in fields)
Console.WriteLine(fi.Name + " = " + fi.GetValue(null));

If you need to filter on only public const fields use

FieldInfo[] fields = type.GetFields(BindingFlags.Static |
BindingFlags.Public);

If you really want only "const" (C#-style, not C++-style) members, as
opposed to static variables, also check the IsLiteral property.

http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.isliteral.aspx
--
Happy Coding!
Morten Wennevik [C# MVP]


bz said:
Hi,

I have a class defined as below:
public class ColumnNames
{
public const string StockID = "StockID";
public const string LevId = "LevId";
public const string ProductieId = "ProductieId";
public const string PartijNummer = "PartijNummer";
public const string ArtNr = "ArtNr";
public const string Opslagplaats = "Opslagplaats";
public const string Geleverd_op = "Geleverd_op";
...

How can I enumerate all the public constants?

Thanks
 
Back
Top