1

I have a List containing several objects. Is there any way I can print out just one of the objects?

Console.WriteLine(myList.ElementAt(1));

This line of code does not give me the object. It does however give me the name of the Class.

  • 3
    You need to print out the object properties one by one. Like `Console.WriteLine(myList.ElementAt(1).Name);` for example. Or override the `ToString` method, but that's usually not the right solution. – DavidG Nov 27 '19 at 12:29
  • 1
    You have to override the .ToString(). For your object. Then you can say myList.ElementAt(1).ToString() – panoskarajohn Nov 27 '19 at 12:30
  • By default, [`ToString`](https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring?view=netframework-4.8) returns a fully-qualified name of the type. If you need to display something different (some of the properties e.g. name) you need to override it. If you need a generic method to print all of the object properties to console, see this question: https://stackoverflow.com/questions/852181/c-printing-all-properties-of-an-object – default locale Nov 27 '19 at 12:36

1 Answers1

4

You have two ways.

  1. Access the properties separately

    var element = myList.ElementAt(1);
    Console.WriteLine("ID:{0}, Name:{1}", element.ID, element.Name);
    

  1. or overload the ToString() for the class

    public class myObject
    {
        public int ID { get; set; }
        public string Name { get; set; }
    
        public override string ToString()
        {
            return string.Format("ID:{0}, Name:{1}", ID, Name);
        }
    }
    

    so you can

    Console.WriteLine(myList.ElementAt(1));
    
fubo
  • 44,811
  • 17
  • 103
  • 137
  • @JohnCarlson if this answer solved the problem, you should accept it as an answer to let other users know. – Frauke Nov 27 '19 at 12:58
  • @Frauke I tried to, but it wouldn't let me at the time. Just came back to my computer. Answer is accepted! :) – John Carlson Nov 27 '19 at 13:51