Why can't I use a generic type for a value type

This may be a basic question, but why can't I apply a generic type to the original type when passing a list of value types to a generic method?

IList<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
Inverse<int>(list);

  public void Inverse<T>(IList<T> list)
        {
            for (i = 0; i <= list.Count / 2; i++)
            {
                int a = list[i] as Int16; //=> does not work
                int b = (int)list[i]; //=> does not work either

            }
         }
+3
source share
5 answers

I would not expect this, you completely missed the point of the general method there, since you assume that the types in IList are "int".

If you have done this:

T a = (T)list[i]

then it will work.

+6
source

Well, since there are no restrictions on T, the second mistake is to prevent something like

Inverse<Person>(new List<Person>());

as for the first error, it asworks only for reference types, and again, since T has no restrictions, the compiler can do nothing.

+2
source

. T, int. int T

+1
int b = Convert.ToInt32(list[i]);

int b = (int)list[i];

, , , , . , # 4, .

EDIT: the statement ascannot work in your example because

The as operator is used to perform some types of conversions between compatible reference types.

link: http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

+1
source

You cannot use how Int16, because you are trying to apply a reference to an object, but Int16(short) is a value type. But your design also missed the generic point: you expect an integer, but you use the general method, so T can really be anything.

0
source

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


All Articles