How to Loop Through All Fields in an Object in C#

How to loop through the properties of a Class?

Something like:

object obj = new object();
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (var p in properties)
{
var myVal = p.GetValue(obj);
}

Note you need to allocate the object and pass it into the PropertyInfo.

Iterate through several field strings

I don't exactly know what the term for this kind of storage is

Those are ValueTuples.

I want to use the Rank property when using other commands

You can create arrays of ValueTuples as well:

var developers = new []
{
(Name: "Sophie", Rank: "DEVELOPER"),
(Name: "Aldrige", Rank: "DEVELOPER"),
};

Which can then be iterated:

foreach (var developer in developers)
{
Console.WriteLine($"{developer.Name} has rank: {developer.Rank}");
}

If you need the names of all developers and members, you could use LINQ:

var members = new []
{
(Name: "John", Rank: "MEMBER"),
(Name: "Hammond", Rank: "MEMBER"),
(Name: "Paul", Rank: "MEMBER"),
};

var names = developers.Concat(members).Select(x => x.Name);


Related Topics



Leave a reply



Submit