Salis Tariq Salis Tariq -4 years ago 128
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()


but it give me every time


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

Answer Source

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

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


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

Printing should be done like this:

foreach (var p in props) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download