Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method in a non-generic class?

Tags:

c#

generics

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;
    }
}
like image 511
John Paul Jones Avatar asked Jan 08 '09 08:01

John Paul Jones


People also ask

Can we have generic method in non-generic class?

Yes, you can define a generic method in a non-generic class in Java.

Can I have a generic method in a non-generic class C#?

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.

Can a non-generic class inherit a generic class?

Yes you can do it.

What is generic and non-generic classes?

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.


3 Answers

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;
    }
}
like image 148
Sander Avatar answered Oct 16 '22 07:10

Sander


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?

like image 29
bruno conde Avatar answered Oct 16 '22 06:10

bruno conde


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;
    }
}
like image 39
Ali Ersöz Avatar answered Oct 16 '22 07:10

Ali Ersöz