Reputation: 896
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
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
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
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
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
Reputation: 222582
You need to access the Name property inside for loop
foreach (var x in lst)
{
Console.WriteLine(x.Name);
}
Upvotes: 1