22

I'm sure I've done this before, but can't find any example of it! Grrr...

For example, I want to convert an IList<T> into a BindingList<T>:

public class ListHelper
{
    public static BindingList<T> ToBindingList(IList<T> data)
    {
        BindingList<T> output = new BindingList<T>();

        foreach (T item in data)
            output.Add(item);

        return output;
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
John Paul Jones
  • 689
  • 4
  • 10
  • 17

3 Answers3

35
ToBindingList <T> (...)

public class ListHelper
{
    public static BindingList<T> ToBindingList<T>(IList<T> data)
    {
        BindingList<T> output = new BindingList<T>();

        foreach (T item in data)
        {
            output.Add(item);
        }

        return output;
    }
}
Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
Sander
  • 25,685
  • 3
  • 53
  • 85
11

Wouldn't this be simpler?

public static class Extensions
{
    public static BindingList<T> ToBindingList<T>(this IList<T> list)
    {
        return new BindingList<T>(list);
    }
}

It's so simple that we don't need an extension method ...

Am I missing something?

bruno conde
  • 47,767
  • 15
  • 98
  • 117
  • Why are you allowed to do that? Is there a constructor in BindingList that takes an array as argument and makes a BindingList out of it? – CodyBugstein Nov 05 '12 at 16:59
  • @Imray it's not an array, it's an `IList`, and there is a constructor that accepts it as an argument: http://referencesource.microsoft.com/#System/compmod/system/componentmodel/BindingList.cs,4f2405ea796059fa,references line 65 – Tyler StandishMan Jan 26 '16 at 17:14
7

You can do this by extension method and it would be better.

public static class Extensions
{
    public static BindingList<T> ToBindingList<T>(this IList<T> list) 
    {
        BindingList<T> bindingList = new BindingList<T>();

        foreach (var item in list)
        {
            bindingList.Add(item);
        }

        return bindingList;
    }
}
Ali Ersöz
  • 15,860
  • 11
  • 50
  • 64