tags:

views:

786

answers:

3

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;
    }
}
+6  A: 

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;
  }
 }
Sander
+4  A: 

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;
    }
}
yapiskan
That's the way I'd do it... maybe even from IEnumerable<T> (sinc all you do is foreach)
Marc Gravell
Yes, IEnumerable would be better.
yapiskan
True. Thanks for tips
John Paul Jones
+5  A: 

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
Sure, this is better.
yapiskan