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