Koosh
Koosh

Reputation: 896

trying to print the contents of a list when using list<class>

I have a class with two variables: Name, Address

I instantiate the class, add values to it, and try to store it in a list. Once I do that I hope to print the Name and Adress on the console but I'm not sure what I'm doing wrong:

public class Test
{
    public string Name { set; get; }
    public string Address { set; get; }
}

static void Main(string[] args)
    {
        Test t = new Test();

        t.Name = "bob";
        t.Address = "CT";

        List<Test> lst = new List<Test>();

        lst.Add(t);

        foreach (var x in lst)
        {
            Console.WriteLine(x);
        }
  }

WHen I do this I simply get the name of my project.ClassName

Upvotes: 0

Views: 68

Answers (5)

Drew Sumido
Drew Sumido

Reputation: 162

If you want to have it print the properties dynamically whenever the class is updated, you can use Json.Net.

class Test
{
 public string Name { set; get; }
 public string Address { set; get; }

 public override string ToString()
 {
    return JsonConvert.SerializeObject(this);
 }

}

Upvotes: 1

evals
evals

Reputation: 1869

for me i will use this

      static void Main(string[] args)
      {
        Test t = new Test();

        t.Name = "bob";
        t.Address = "CT";

        List<Test> lst = new List<Test>();
        lst.Add(t);
        lst.ForEach(show);
    }

    private static void show(Test obj)
    {
        Console.WriteLine(obj.Name);
        Console.WriteLine(obj.Address);
    }

Upvotes: 1

Link
Link

Reputation: 1711

You can utilize the ToString in your class. When passed your class-instance to the Console.WriteLine function, this ToString-function is called. For further information check the documentation for Console.WriteLine and object.ToString().

public class Test
{
    public string Name { set; get; }
    public string Address { set; get; }

    public override string ToString()
    {
        return $"Name: {Name} Address: {Address}";
    }
}

static void Main(string[] args)
{
    Test t = new Test();

    t.Name = "bob";
    t.Address = "CT";

    List<Test> lst = new List<Test>();

    lst.Add(t);

    foreach (var x in lst)
    {
        Console.WriteLine(x);
    }
}

This will output:

Name: bob Address: CT

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56433

Simply, override ToString and everything else should work as you'd expect it to.

Example:

class Test
{
     public string Name { set; get; }
     public string Address { set; get; }

     public override string ToString(){
         return $"name: {Name}, address: {Address}";
     }
}

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222582

You need to access the Name property inside for loop

foreach (var x in lst)
{
    Console.WriteLine(x.Name);
}

Upvotes: 1

Related Questions