1

when i try to print a list of objects in c# it does not print what i want, let me demonstrate.

example:

public class Classname
    {
        public string hello;
        public string world;

        
    }

namespace inloggning
{

    class Program
    {
        static void Main(string[] args)
        {
            List<object> listOfObjects = new List<object>();

            Classname example = new Classname();
            example.hello = "hello";
            example.world = "world";

            listOfObjects.Add(example);

            Console.WriteLine(listOfObjects[0]);

        }

    }
}

when i run this it prints out "inloggning.Classname". Can someone help me understand why and how i can fix it so it prints "hello" and "world".

2
  • 1
    Because you didn't override ToString: learn.microsoft.com/en-us/dotnet/csharp/programming-guide/…. Or alternatively you would have to explicitly specify which members you want to print to console Commented Jul 31, 2020 at 17:42
  • Just implement ToString() Commented Jul 31, 2020 at 17:46

2 Answers 2

2

Add a toString method to your object, like that

public string overide ToString()
{
return hello + " " + world;
}

EDIT: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method

Sign up to request clarification or add additional context in comments.

5 Comments

This will work. Background: in C#, the ToString method on a class determines what is printed to the console when you log it. By default for all classes, this just writes the class name. You can override it to show something more helpful.
If you want to write less code for an object with many properties, you can also serialize to JSON and log that to the console.
FYI the return type is missing in your method declaration
do you still think i will be able to do this if the strings are not identified yet.
@edwardthecoder a null value will be replaced by the empty string if you try to concatenate it to a string, so it won't error but you might only get a space returned from the method. From Ani's answer to another post
0

Change the WriteLine statement like this:

Console.WriteLine(((ClassName)listOfObjects[0]).hello+(ClassName)listOfObjects[0]).world);

2 Comments

thank you for this answer! it really helped. I now wonder if there is a way that i can print all objects in the listofobjects list. using foreach or something similar?
Your welcome, you can use: for (var i = 0; i < listOfObjects.Count; i++) { Console.WriteLine(((Classname)listOfObjects[i]).hello + ((Classname)listOfObjects[i]).world); }