Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Method for a List

Tags:

c#

I have a List of a class Order which implements IComparable and override the Tostring method

Order class:

public class Order : IComparable
    {
        public int id { get; set; }
        public DateTime date { get; set; }
        public int CompareTo(object obj)
        {
            if (obj == null)
            {
                return 1;
            }
            else
            {
                Order order = obj as Order;
                if (order == null)
                {
                    throw new ArgumentException("object is not an order");
                }
                return this.date.CompareTo(order.date);
            }
        }
        public override string ToString()
        {
            return this.id+"--"+this.date.ToString("dd/MM/yyyy");
        }
    }

Now i added an extension Method Show to List and it is working as i expected

Extension Class

public static class ListExtension

    {
        public static void Show(this List<Order> list)
        {

            foreach (var item in list)
            {
                Console.WriteLine(item.ToString());
            }
        }
    }

Now i would like to turn my method Show Generic :

 public static class ListExtension<T>
   {
        public static void Show(this List<T> list)
        {

            foreach (var item in list)
            {
                Console.WriteLine(item.ToString());
            }
        }
    }

But i can not call the generic extension method. Can you help me .

like image 332
Ghassen Avatar asked Mar 14 '23 19:03

Ghassen


2 Answers

You missed the <T> after the name of the function to make it generic:

public static class ListExtension
{
    public static void Show<T>(this List<T> list)
    {
        foreach (var item in list)
        {
            Console.WriteLine(item.ToString());
        }
    }
}
like image 58
Andrew Avatar answered Mar 28 '23 11:03

Andrew


The extension can be made more generic and faster (I think):

public static void Show<T>(this IList<T> list)
{
    var str = String.Join(Environment.NewLine, list);
    Console.WriteLine(str);
}
like image 38
Alexei - check Codidact Avatar answered Mar 28 '23 13:03

Alexei - check Codidact