0

I've tried for 2 days to find something that will work and none of the examples I have found are working.

What I need is to be able to get a list of public properties from an instantiated class.

For Instance:

MyClass has the following definition:

public class MyClassSample : MyDC
{
  public string ReportNumber = "";
  public string ReportDate = "";

  public MyClassSample()
  {
  }
}

What I need is a way to simply return an array that has ["ReportNumber"]["ReportDate"] in it from the above class.

Here is my most recent attempt, just to add the property names to a string:

    string cMMT = "";

    Type t = atype.GetType();
    PropertyInfo[] props = t.GetProperties();
    List<string> propNames = new List<string>();
    foreach (PropertyInfo prp in props)
    {
        cMMT = cMMT + prp.Name + "\n";
    }

I think I am missing something basic and simple, but for some reason I cannot see it right now. Any help would be appreciated.

2
  • 2
    I suggest you learn the difference between fields and properties before you dive into reflection ;) Commented May 16, 2012 at 15:54
  • Please read also this article how to handle with String dotnetperls.com/convert-list-string Commented May 16, 2012 at 16:00

2 Answers 2

6

Those aren't properties. Those are fields.

So you can do this:

FieldInfo[] fields = t.GetFields();

Or you can change those into properties:

public string ReportNumber { get; set; }
public string ReportDate { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

1

change this

public string ReportNumber = "";
public string ReportDate = "";

to this

public string ReportNumber { get; set; }
public string ReportDate { get; set; }

and then,

List<string> propNames = new List<string>();

foreach (var info in atype.GetType().GetProperties())
{
   propNames.Add(info.Name);
}

The result wold be a list (propName) with two positions with the name of your properties

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.