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;
}
}
Yes, you can define a generic method in a non-generic class in Java.
Yes, There are two level where you can apply generic type . You can apply generic type on Method level as well as Class level (both are optional). As above example you applied generic type at method level so, you must apply generic on method return type and method name as well. You need to change a bit of code.
Yes you can do it.
A Generic collection is a class that provides type safety without having to derive from a base collection type and implement type-specific members. A Non-generic collection is a specialized class for data storage and retrieval that provides support for stacks, queues, lists and hashtables.
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;
}
}
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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With