❔ 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!
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
students[0]
The first item in students list
that outputs namespace.Student and im not sure why. all the other indexing syntax does the same 😭
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
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!
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
or, more concisely
OMG that works perfectly! Thank you for explaining it too I cant thank you enough!
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 typereferenceWas 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.