Ghassen
Ghassen

Reputation: 1206

Extension Method for a List

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 .

Upvotes: 4

Views: 104

Answers (2)

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23108

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);
}

Upvotes: 2

Andrew
Andrew

Reputation: 261

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());
        }
    }
}

Upvotes: 5

Related Questions