-3

I have a class Class1

public class Class1
{
    public string ABC { get; set; }
    public string DEF { get; set; }
    public string GHI { get; set; }
    public string JLK { get; set; }
}

How can I get a list of, in this case 'ABC', 'DEF', ... I want to get the name of all public fields.

I tried the following:

Dictionary<string, string> props = new Dictionary<string, string>();

foreach (var prop in classType.GetType().GetProperties().Where(x => x.CanWrite == true).ToList())
{
    //Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(classitem, null));
    //objectItem.SetValue("ABC", "Test");
    props.Add(prop.Name, "");
}

And:

var bindingFlags = BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public;
var fieldValues = classType.GetType()
                            .GetFields(bindingFlags)
                            .Select(field => field.GetValue(classType))
                            .ToList();

But neither gave me the wanted results.

Thanks in advance

Dieter B
  • 1,142
  • 11
  • 20

2 Answers2

1

Try something like this:

using System;
using System.Linq;

public class Class1
{
    public string ABC { get; set; }
    public string DEF { get; set; }
    public string GHI { get; set; }
    public string JLK { get; set; }
}

class Program
{
    static void Main()
    {
        // Do this if you know the type at compilation time
        var propertyNames 
            = typeof(Class1).GetProperties().Select(x => x.Name);

        // Do this if you have an instance of the type
        var instance = new Class1();
        var propertyNamesFromInstance 
            = instance.GetType().GetProperties().Select(x => x.Name);
    }
}
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
1

Isn't clear what classType means in your original code.

If it's a instance of Class1 that should work; if you already got a System.Type, your classType.GetType() will not return your properties.

Also, you should be aware of properties and fields difference, as it matters to reflection. The code below lists your original properties, skips a property without setter and also a field, just to demonstrate how that conceptual difference affects your code.

class Program
{
    static void Main(string[] args)
    {
        var classType = typeof (Class1);
        foreach (var prop in classType.GetProperties().Where(p => p.CanWrite))
        {
            Console.WriteLine(prop.Name);
        }

        foreach (var field in classType.GetFields())
        {
            Console.WriteLine(field.Name);
        }
    }
}

public class Class1
{
    public string ABC { get; set; }
    public string DEF { get; set; }
    public string GHI { get; set; }
    public string JLK { get; set; }

    public string CantWrite { get { return ""; } }
    public string Field = "";
}
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162