Home > other >  Can a generic method access the array elements of a generic parameter?
Can a generic method access the array elements of a generic parameter?

Time:01-08

I call FunctionB passing a string array using generic method like this.

string[] array1 = {"data1", "data2", "data3"};

void FunctionA ( )
{
    FunctionB ( array1 );
}

void FunctionB <T> (T arg)
{
    print (typeof(T));
}

I got the data type of arg. Is there any way to have array1's data elements in FunctionB ?

CodePudding user response:

You can create another method, which has an array as a parameter and spring each element of the array. Example:

void FunctionB <T> (T[] arg)
{
    foreach(T item in arg)
    {
        print (item);
    }
}

CodePudding user response:

I supposed you need to use pattern matching. Here is how to do it:

static class Program
{
    static void FunctionB<T>(T arg)
    {
        if (arg is string[] array)
        {
            foreach (var item in array)
            {
                Console.WriteLine(item);
            }
        }
    }
    static void Main(string[] args)
    {
        // TODO: Put code here
        string[] array1 = { "data1", "data2", "data3" };

        FunctionB(array1);
        //data1
        //data2
        //data3
    }
}
  •  Tags:  
  • Related