12

I've got a struct that looks like this:

public struct MyStruct
{
    public const string Property1 = "blah blah blah";
    public const string Property2 = "foo";
    public const string Property3 = "bar";
}

I want to programmatically retrieve a collection of MyStruct's const properties' values. So far I've tried this with no success:

var x = from d in typeof(MyStruct).GetProperties()
                    select d.GetConstantValue();

Anyone have any ideas? Thanks.

EDIT: Here is what eventually worked for me:

from d in typeof(MyStruct).GetFields()
select d.GetValue(new MyStruct());

Thank you Jonathan Henson and JaredPar for all your help!

SquidScareMe
  • 3,108
  • 2
  • 24
  • 37

3 Answers3

19

These are fields not properties and hence you need to use the GetFields method

    var x = from d in typeof(MyStruct).GetFields()
            select d.GetRawConstantValue();

Also I believe you're looking for the method GetRawConstantValue instead of GetConstantValue

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • I know this is an old question/answer but thank you. You are the first person to point out that they are fields not properties. – James Mar 12 '12 at 21:44
  • When I try to access var x I get an exception: "Operation is not valid due to the current state of the object." - any ideas? – user3147973 Oct 20 '21 at 01:24
3

Here's a bit different version to get the actual array of strings:

string[] myStrings = typeof(MyStruct).GetFields()
                     .Select(a => a.GetRawConstantValue()
                     .ToString()).ToArray();
u84six
  • 4,604
  • 6
  • 38
  • 65
2

GetProperties will return your Properties. Properties have get and/or set methods.

As of yet your structure has no properties. If you want properties try:

private const string property1 = "blah blah";

public string Property1
{
    get { return property1; }
}

furthermore, you could use GetMembers() to return all of your members, this would return your "properties" in your current code.

Jonathan Henson
  • 8,076
  • 3
  • 28
  • 52
  • 1
    you can also set values with a Property such as: private string property1; public string Property1 { get { return property1; } set { property1 = value; } } Also, in C# v 3.5 and later, you can just do get; and set; without actually declaring your encapsulated object. – Jonathan Henson May 03 '11 at 18:23