Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a generic type where T also can be int32,but not only a class

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?

like image 382
Artem G Avatar asked Nov 30 '22 12:11

Artem G


2 Answers

Don't use either struct or class as a generic constraint. You can then use either.

like image 192
Servy Avatar answered Dec 05 '22 02:12

Servy


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);
}
like image 32
Travis J Avatar answered Dec 05 '22 01:12

Travis J