Amit Bisht
Amit Bisht

Reputation: 5136

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

Upvotes: 23

Views: 25884

Answers (4)

Sonu Rajpoot
Sonu Rajpoot

Reputation: 505

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;
  }

Upvotes: 4

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

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>();

Upvotes: 33

baryo
baryo

Reputation: 1461

you need to add the generic type parameter to the method signature.

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

Upvotes: 2

Sergey Litvinov
Sergey Litvinov

Reputation: 7458

You need to specify generic type <T> in the method name itself like this:

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

Upvotes: 9

Related Questions