AlexanderK
AlexanderK

Reputation: 365

What's wrong with printing from the List of classes?

MyData data = new MyData { MyInt = 1, MyString = "Smith" };
MyData data1 = new MyData { MyInt = 3, MyString = "Wesson" };
MyData data2 = new MyData { MyInt = 2, MyString = "Colt" };
List<MyData> lst = new List<MyData>();
lst.Add(data);
lst.Add(data1);
lst.Add(data2);

Console.WriteLine("\nBefore sort:");
foreach (MyData MyInt in lst)
{
    Console.WriteLine((MyInt));
    Console.WriteLine(lst.ToString());
} 

Just made simple list for practice, but in the output i have something wrong. enter image description here

Why it's shown that way? I've expected to get it's content. Two different ways gave me the same result. May be i'm wrong with list populating?

Upvotes: 0

Views: 52

Answers (3)

ManoDestra
ManoDestra

Reputation: 6473

If you wish to output each MyData object, then you'll need to implement your own ToString method by overriding the default which is the result you're seeing above (displaying merely the object reference). You should also call your variables something different. Don't use MyInt in your for loop. Call it something sensible like data. Don't prefix your classes with My either. Bad practice.

Upvotes: 0

user47589
user47589

Reputation:

By default, your MyData class uses the implementation of ToString() it inherited from System.Object. That function returns very generic information about the class - pretty much just the class name, and some limited information on any generic type parameters.

If you wish ToString() to display different information, you will need to override it yourself:

public override string ToString() 
{
    return String.Format("{0} {1}", MyInt, MyString);
}

Upvotes: 5

Dan Field
Dan Field

Reputation: 21641

MyInt will be a varabile of type MyData - not the MyInt property of the object MyData. Does the MyData class override ToString()? That's what Console.WriteLine will be looking for when it tries to write the object - otherwise, it will use the default from Object, which is what you're seeing.

You probably want something more like this:

Console.WriteLine("\nBefore sort:");
foreach (MyData myData in lst)
{
    Console.WriteLine(myData.MyInt);
} 

Which is instead writing the MyInt property of the MyData object.

If you want, you could override the ToString method like so in the MyData class/struct:

public override string ToString()
{
    return MyInt.ToString(); // assuming you just want to see the MyInt property...
}

Upvotes: 1

Related Questions