I want to create a generic stack
I have a Node class
public class GenericNode<T> where T : class
{
public T item;
public GenericNode<T> next;
public GenericNode()
{
}
public GenericNode(T item)
{
this.item = item;
}
}
And can use it like
GenericNode<string> node = new GenericNode<string>("one")
But I can't use it also like
GenericNode<int> node = new GenericNode<int>(1)
because int is not a reference type (not a class) and I use where T: class But List is also not a reference type.
How can I fix my problem?
Don't use either struct
or class
as a generic constraint. You can then use either.
Using the struct
constraint (or class
depending on which version of the question you look at) means that the type for T
cannot be nullable and will throw an exception when you try to use <string>
.
Removing it will allow you to do the steps you want.
public class GenericNode<T> where T : IConvertible
{
public T item;
public GenericNode<T> next;
public GenericNode()
{
}
public GenericNode(T item)
{
this.item = item;
}
}
void Main()
{
GenericNode<string> node = new GenericNode<string>("one");
GenericNode<int> node2 = new GenericNode<int>(1);
}
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