0

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

Salis Tariq
  • 93
  • 1
  • 1
  • 8

3 Answers3

5

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);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

if you are using c#6 there is now a nice nameof keyword

nameof(email) returns "email"

then their is the earlier CallerMemberName attribute that can be attached to a method call as so

public void MemberName([System.Runtime.CompilerServices.CallerMemberName] string memberName = "")

then you have reflection

Console.WriteLine("Properties of System.Type are:");
foreach (PropertyInfo myPropertyInfo in typeof(MyClass).GetProperties())
{
    Console.WriteLine(myPropertyInfo.ToString());
}
MikeT
  • 5,398
  • 3
  • 27
  • 43
0

Other people have similar answers I know but I just wanted to add a few other items. First the code:

IEnumerable<string> names = typeof(MyClass ).GetProperties().Select(prop => prop.Name);

foreach (var name in names)
{
   Console.WriteLine(name);
}

As others have pointed out, you're interested in the properties here (not fields). If I change the GetProperties() call to GetFields(), it'll return an empty collection. If, however, I change it to GetFields(BindingFlags.NonPublic | BindingFlags.Instance) it'll give me the name of the backing field (which I suspect isn't what you're looking for).

The other thing I'd like to add is that ToString() doesn't always do what you're expecting it to. In many cases (like the above), you just get the name of the type itself (not the content). As a corollary, you generally can't just do ToString() to get a string representing the concatenated value of all of the items in a collection. You could write an extension method to do that if you wanted to though.