Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method inside non-generic class

I'm using .net framework 4.0
I want to create a generic method inside a non-generic class but it gives me compile time error

Error :The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

  public class BlIAllClass
    {
        public static List<T> xyz()
        {
            List<T> cc = new List<T>();
            return cc;
        }
    }

Also there is a question asked by John Paul Jones Generic Method in non generic class
There he mentioned that it is possible to create generic method inside non-generic class.
Then what's wrong with my code.
Is it framework version related issue or i'm missing something

like image 988
Amit Bisht Avatar asked May 19 '15 06:05

Amit Bisht


2 Answers

Your method is not a generic. A generic method is a method that is declared with type parameters.

Change your method to:

public static List<T> xyz<T>()
{
    List<T> cc = new List<T>();
    return cc;
}

Also you can just change method implementation as: return new List<T>();

like image 117
Farhad Jabiyev Avatar answered Sep 26 '22 00:09

Farhad Jabiyev


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. See Following.

 public static List<T> xyz<T>()
  {
   List<T> cc = new List<T>();
    return cc;
  }
like image 38
Sonu Rajpoot Avatar answered Sep 27 '22 00:09

Sonu Rajpoot