Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get collection of values from struct's const properties

Tags:

c#

reflection

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!

like image 407
SquidScareMe Avatar asked May 03 '11 18:05

SquidScareMe


2 Answers

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

like image 161
JaredPar Avatar answered Oct 26 '22 17:10

JaredPar


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

string[] myStrings = typeof(MyStruct).GetFields()
                     .Select(a => a.GetRawConstantValue()
                     .ToString()).ToArray();
like image 22
u84six Avatar answered Oct 26 '22 17:10

u84six