How to create a generic type, where T can also be int32, but not just a class

I want to create a shared 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 as

 GenericNode<string> node = new GenericNode<string>("one") 

But I can’t use it either , for example

 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?

+4
source share
3 answers

Using a struct constraint (or class depending on which version of the question you are looking at) means that the type for T cannot be null and will throw an exception when trying to use <string> .

Deleting this file will allow you to perform the necessary actions.

 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); } 
+7
source

Do not use either struct or class as a general restriction. Then you can use.

+8
source

Remove the class constraint:

 public class GenericNode<T> /* where T : class*/ 

If you leave this restriction, it will allow your class to work with any type, whether it be a value or a reference type.

+6
source

Source: https://habr.com/ru/post/1486702/


All Articles