简体   繁体   中英

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 comile 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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM