C
C#16mo ago
profit

❔ How would you index this or access anything in this List?

I'm new and trying to learn more advanced lists. i found this code on a learning forum and I think its pretty neat, and i want to learn more about how to work with it!
Ive been trying to figure out how to index it and thats where im running into problems. I've looked up just about every keyword i can think of and nothing is working or it just returns namespace.Student 😭 I would really appreciate if someone could help or explain! class Student { public int Id ; public string Name; } class ProgramMain { static void Main(string[] args) { var students = new List<Student>() { new Student(){ Id = 1, Name="Bill"}, new Student(){ Id = 2, Name="Steve"}, }; } } } (If having the link to the page i found it on would help here it is https://www.tutorialsteacher.com/csharp/csharp-list)
8 Replies
phaseshift
phaseshift16mo ago
students[0] The first item in students list
profit
profitOP16mo ago
that outputs namespace.Student and im not sure why. all the other indexing syntax does the same 😭
phaseshift
phaseshift16mo ago
It doesn't output anything by itself. You're hiding details Your question is about indexing then you say the output is wrong. So what is exactly the problem? A complete example would help If you're expecting console writeline to print each field/member of your class, no, it doesn't do that. It's nothing to do with indexing, you just have to write your own print method
profit
profitOP16mo ago
I see, thank you! so I just want to figure out how to (as an example) print the first Id in the list. Or any other variables I set. How would i get a similar result of what students[0] would be in a more simple list. im somewhat new so I'm not super familiar with the terminology so please let me know if i need to explain what im asking further!
JakenVeina
JakenVeina16mo ago
give us the code you're asking about, and we can explain it if you want to "print the first Id in the list" you need to A) retrieve the first item in the list B) retrieve the .Id value of that object C) print it
var firstStudent = students[0];
var firstStudentId = students.Id;
Console.WriteLine(firstStudentId);
var firstStudent = students[0];
var firstStudentId = students.Id;
Console.WriteLine(firstStudentId);
or, more concisely
Console.WriteLine(students[0].Id);
Console.WriteLine(students[0].Id);
profit
profitOP16mo ago
OMG that works perfectly! Thank you for explaining it too I cant thank you enough!
Florian Voß
Florian Voß16mo ago
because the type doesn't ovveride ToString(). When you console.writeline an object, it calls ToString() on the object, and because it doesn't override Object.ToString() you see default behaviour which is to output the typereference
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server