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".

  • 1
    Because you didn't override `ToString`: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method. Or alternatively you would have to explicitly specify which members you want to print to console – UnholySheep Jul 31 '20 at 17:42
  • Just implement `ToString()` – IC_ Jul 31 '20 at 17:46

2 Answers2

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

Bestter
  • 877
  • 1
  • 12
  • 29
  • 1
    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. – JamesFaix Jul 31 '20 at 17:44
  • 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. – JamesFaix Jul 31 '20 at 17:44
  • 1
    FYI the return type is missing in your method declaration – Rand Random Jul 31 '20 at 17:49
  • 1
    do you still think i will be able to do this if the strings are not identified yet. –  Jul 31 '20 at 17:56
  • @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](https://stackoverflow.com/a/4206185/7908554) – Jacob Huckins Jul 31 '20 at 18:05
0

Change the WriteLine statement like this:

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

mahdi b
  • 37
  • 3
  • 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? –  Jul 31 '20 at 20:00
  • Your welcome, you can use: ```for (var i = 0; i < listOfObjects.Count; i++) { Console.WriteLine(((Classname)listOfObjects[i]).hello + ((Classname)listOfObjects[i]).world); }``` – mahdi b Aug 02 '20 at 06:22