C
C#2mo ago
Bailey

Reflection and customclass in list properties c#

Hello, I am trying to solve the folowing. I got a list<person> I want to use reflection to get the list and walk through the properties. I have put some fictional code in this. The problem is with the list. How to solve this so that I can use the for or foreach loop to go to the next level the custom class properties. namespace reflection { internal class Program { // just sample static void Main(string[] args) { List<Person> list = new List<Person>(); list.Add(new Person() { Age= 2, Name="a"}); list.Add(new Person() { Age = 3, Name = "b" }); var analyse = new analyse(); analyse.analyseThis(list); Console.ReadLine(); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace reflection { public class Person { public string Name { get; set; } public int Age { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace reflection { public class analyse { public void analyseThis(object test) { var data = test.GetType().GenericTypeArguments[0]; // how to get this working foreach (var customClass in test.GetType().) { // below works for clASS. Type type = customClass.GetType(); PropertyInfo[] propertyInfos = customClass.GetType().GetProperties(); // here the code } } } }
7 Replies
Anton
Anton2mo ago
data.GetProperties() ah I see cast it to IList for indexing or to IEnumerable for foreach iteration
douchebag
douchebag2mo ago
what is this test.GetType().? "test"? what variable is this .Properties()?
X
X2mo ago
Hi, are you there?
douchebag
douchebag2mo ago
Hi
X
X2mo ago
hi, sorry for delayed reply.
douchebag
douchebag2mo ago
It's fine. What's up?
Bailey
Bailey2mo ago
Hi Anton, 'll try it tomorrow. Thanks this is thew for loop which i cant get to work. It cant recognise the list. Thats why I added comment above. I'll try tomorrow the feedback of Anton Hi, I found the sollution for the problem. You pointet me to the rigt direction. the loop should be like below if (test is IList list) { foreach (var item in list) { Console.WriteLine(item); } } --close
Want results from more Discord servers?
Add your server