Salis Tariq Salis Tariq - 3 months ago 8
C# Question

How to print prop name of a class in C#

I have a class of name MyClass Which has many properties

class MyClass
{
public int Id { get; set; }

public string Name { get; set; }

public string email { get; set; }

public string password { get; set; }

public string city { get; set; }
}


I want to print the properties name in Console.writeline like

static void Main(string[] args)
{
MyClass m = new MyClass();
var s = m.GetType()
.GetFields();
Console.WriteLine(s);



Console.ReadKey();
}


but it give me every time

System.Reflection.FieldInfo[]


Kindly tell me how can i do this or i can do this or not

Answer

Although syntactically they look similar, properties are not fields. Use GetProperties instead:

var props = m.GetType().GetProperties();

or

var props = typeof(MyClass).GetProperties();

Printing should be done like this:

foreach (var p in props) {
    Console.WriteLine(p.Name);
}
Comments