-2

I have a little console program that prints out properties for a given class.

It works, but I was wondering if there's a way of doing this without having to a instantiate new class.

I'm asking because I want to get the class name and all the class properties of every class in my project.

If I could do that without having to instantiate each class, it would really cut down on the programming.

namespace ObjectViewer
{
    class PropertyLister
    {
        static void Main(string[] args)
        {
            Programmer programmer = new Programmer() { Id = 123, Name = "Joe", Job = "Programmer" };

            printProperties(programmer);

            Console.ReadLine();
        }

        public static void printProperties(Object jsonObject)
        {
            JObject json = JObject.FromObject(jsonObject);
            Console.WriteLine("Classname: {0}\n", jsonObject.ToString());
            Console.WriteLine("{0,-20} {1,5}\n", "Name", "Value");
            foreach (JProperty property in json.Properties()) { 
                Console.WriteLine("{0,-20} {1,5:N1}",  property.Name, property.Value);
            }
        }
    }
}
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185

2 Answers2

2

You can use reflection:

class ClassA
{
    public string NameField;

    public string NameProperty { get; set; }
}

public class Program
{
    public static void Main()
    {
        Type t = typeof(ClassA);

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

        foreach(var prop in t.GetProperties())
        {
            Console.WriteLine(prop.Name);
        }
    }
}

This will output:

NameField
NameProperty
Marco Fatica
  • 937
  • 7
  • 12
0

You can get all the properties of a type with the .GetProperties() method for a given type.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Lewis Taylor
  • 673
  • 3
  • 13