Reputation: 19
c# code to return generic List from Class1
private void Form1_Load(object sender, EventArgs e)
{
Class1<int> obj = new Class1<int>();
List<int> covariant = new List<int>();
covariant = obj.mark();
System.Console.WriteLine(covariant[0]);
}
public class Class1<T>
{
public List<T> mark()
{
List<object> covariant = new List<object>();
covariant.Add(5); *unable to get value in covariant list defined. Getting null vlaue*
return covariant as List<T>;
}
}
unable to get value in covariant list defined. Getting null vlaue unable to get value in covariant list defined. Getting null vlaue unable to get value in covariant list defined. Getting null vlaue unable to get value in covariant list defined. Getting null vlaue
Upvotes: 0
Views: 63
Reputation: 1988
I think you should not use Generics
if you are going to explicitly use int
inside your method.
This should be your first hint
that you should not use generics in the first place.
Here is what your class might look like with a more proper use of generics.
public class Class1<T>
{
private List<T> covariants = new List<T>();
public List<T> mark(T item)
{
covariants.Add(item);
return covariants;
}
}
var s = new Class1<int>.mark(5)
will return a list of count 1.
s.mark(10)
will return a list with two items.
For more info about c# generics you can read the docs -> https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/
Upvotes: 1