ToString () does not return the expected string


using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3Generics
{
    class Program
    {
        static void Main(string[] args)
        {
            ScheduleSelectedItems sitems = new ScheduleSelectedItems("Yusuf");
            ScheduleSelectedItemsList slist = new ScheduleSelectedItemsList();
            slist.Items.Add(sitems);
            Console.Write(slist.Items[0].ToString());
            Console.ReadKey();
        }
    }
    public class ScheduleSelectedItems
    {
        private string Ad;

        public ScheduleSelectedItems(string ad)
        {
            Ad = ad;
        }
    }

    public class ScheduleSelectedItemsList
    {
        public List Items;

        public ScheduleSelectedItemsList()
        {
            Items = new List();
        }
    }
}

How can I add "yusuf" to my console?

+3
source share
4 answers
public class ScheduleSelectedItems
    {
        private string Ad;

        public ScheduleSelectedItems(string ad)
        {
            Ad = ad;
        }

        public override string ToString()
        {
            return this.Ad;
        }
    }
+15
source

What BFree said with a slight modification to make it singular, not multiple:

public class ScheduleSelectedItem
{
    private string Ad;

    public ScheduleSelectedItem(string ad)
    {
        Ad = ad;
    }
    public override string ToString()
    {
        return this.Ad;
    }
}

In addition, you need the Add method for your list. Although you are at it, why not just inherit from the list class:

public class ScheduleSelectedItemsList : List<ScheduleSelectedItem>
{

}

Or you can just create an alias like:

using ScheduleSelectedItemsList = List<ScheduleSelectedItem>;

In any case, you can use the new code as follows:

class Program
{
    static void Main(string[] args)
    {
        var slist = new ScheduleSelectedItemsList() 
        { 
            new ScheduleSelectedItem("Yusuf") 
        };

        //write every item to the console, not just the first
        slist.All(item => Console.Write(item.ToString()) );
        Console.ReadKey();
    }
}
+5
source

ScheduleSelectedItems:

    public override string ToString() {
        return Ad;
    }

, .

+3

toString() ScheduleSelectedItems, "Ad".

+2

Source: https://habr.com/ru/post/1702481/


All Articles