0
public class item
{
  public int x;  
  public string s;
  public item ()
  {}
}

Then in the main method, I try to create a list and print out the elements in it.

{
  item first=new item();
  first.x=5;
  first.s="Hello";
 
  item second =new item();
  second.x=6;
  second.s="world";

  List <item> myItem= new List <item> ();
  myItem.Add(first);
  myItem.Add(second);
  
  foreach (item element in myItem)
  {
    Console.WriteLine(element);
  }
}

There is no syntax error, but terminal returns nothing when I try to run the code above.

rioV8
  • 24,506
  • 3
  • 32
  • 49
Jackie Ma
  • 15
  • 5
  • Try to use your objects fields, Console.WriteLine("x: " + element.x.ToString() + " s: " + element.s); This may help https://stackoverflow.com/questions/360277/what-is-the-best-way-to-dump-entire-objects-to-a-log-in-c – Eren Peksen Mar 20 '21 at 09:27
  • Please provide a [mcve] rather than snippets. I would expect that to print `item` twice, as the default implementation for `ToString()` just returns the class name. (As an aside, I'd strongly suggest learning and following C# naming conventions as early as possible.) – Jon Skeet Mar 20 '21 at 09:37
  • _"There is no syntax error"_ false. This doesn't compile. `first.x=5;` will not work, as `int x` has no accessor defined, thus is private. And you are using `y`, which is not defined. – JHBonarius Mar 20 '21 at 09:48
  • I fixed the typo and adding access modifier to the field variables, so that it will not confuse people, thank you. – Jackie Ma Mar 20 '21 at 10:12
  • We're still missing a [mcve]. Again, I'd expect that to print `item` twice. If it's not printing anything for you, there may be something else going on... but we can't help you if we can't reproduce it. – Jon Skeet Mar 20 '21 at 16:20

4 Answers4

0

The compiler will not magically know how to convert your custom type to a string. However, each class derives from the object class, that has a (virtual) ToString method. If not overwritten, it will print the class name. You can override it yourself in the item class. E.g.

public override string ToString()
{
    return "x: " + x + ", s: " + s;
}
JHBonarius
  • 10,824
  • 3
  • 22
  • 41
0

The approach you are following can be improved. See this- Getter and Setter declaration in .NET

and you have defined variable in class as

int x;
string s;

and using as

first.x=5;
first.y="Hello"; // what is y here? It is not defined in your model class

in your approach, list elements can be printed like this (currently properties in your item class are private, you have make them public or see @jhbonarius answer for toString method)

foreach (item element in myItem)
  {
    Console.WriteLine(element.x +" "+element.s);
  }
Abhi
  • 614
  • 2
  • 12
  • 26
  • No. If the accessor is not defined, it is private by default. So x and s are not accessible from outside of the class – JHBonarius Mar 20 '21 at 09:44
  • yes, thanks @JHBonarius, I have noted that in the answer. – Abhi Mar 20 '21 at 09:46
  • Thank you @Abhishek and JHBonarius for pointing out the issues. So is this saying that can only use 'Console.WriteLine (element);' when the items in the lists are the same variable type, i.e. all int or all string? – Jackie Ma Mar 20 '21 at 10:24
0

Please, use PascalCase for definitions of classes and fields.

public class Item
{
    public string A { get; set; }
    public int X { get; set; }
}

The WriteLine method automatically calls the ToString method to 'transform' the object into a string.

If you want to see the values ​​of the fields you have to write:

Console.WriteLine(“A: ” + item.A + “ X: “ + item.X);
// or w/ string interpolation
Console.WriteLine($”A: {item.A} X: {item.X}”);

// console output
A: ‘value of A’ X: ‘value of X’

You could also override the ToString method within the ‘Item’ class.

public class Item
{
    public string A { get; set; }
    public int X { get; set; }

    public override string ToString()
    {
        return "A: " + A + " X: " + X;
    }
}

And to write the value on console just write

Console.WriteLine(item);

// console output
A: ‘value of A’ X: ‘value of X’
stfno.me
  • 898
  • 7
  • 24
0

The problem you have is that you are trying to print the whole item. You can do that if you implement a ToString() method (like in the answer above by JHBonarius) in your "item" class and then call :

foreach (item element in myItem)
{
    Console.WriteLine(element.ToString()); .
}

Or you try to print the exact propertiest of your "item" like:

foreach (item element in myItem)
{
    Console.WriteLine("x: " + element.x.ToString() + " s: " element.s.ToString()); 
}

And definitely change your class definition to the one @SteeBono recommends above .

public class item
{
    public int x { get; set; }
    public string s { get; set; }
}

In case you want to print out your properties dynamically you can use iterate through all of the properties of you class ("item" in this case) :

foreach (var element in myItem)
{
    elementPrintData += "Element : \n";

    foreach (var fromProp in typeof(item).GetProperties())
    {
        var toProp = typeof(item).GetProperty(fromProp.Name);
        var toValue = toProp.GetValue(element, null);
        string val = "";
        if (toValue != null)
        {
            // this will try to print DateTime if present, might need to add null check
            if (toProp.PropertyType == typeof(DateTime?) || toProp.PropertyType == typeof(DateTime))
                val = ((DateTime)toValue).ToString("dd/MM/yyyy");
            else
                val = toValue.ToString();
        }

    // this will print the property name with the value (int, string, bool, double...) 
    //if it is not a collection/list
    // each property will go into a new line because of the " \n"
        if (!string.IsNullOrEmpty(val) && !val.Contains("System.Collections"))
            elementPrintData += toProp.Name + ": " + val + " \n";
   }
}
terodaktil
  • 106
  • 3