Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array

Tags:

c#

generics

In the sample code below, why does the call to ArrayMethod fail for a genric type when I don't include the class constraint

public interface IFoo { }
public interface IBar : IFoo { }

public class Test
{
    public void ClassConstraintTest<T>() where T : class, IFoo
    {
        T[] variable = new T[0];
        ArrayMethod(variable);
    }

    public void GenericTest<T>() where T : IFoo
    {
        T[] variable = new T[0];
        ArrayMethod(variable);  // Compilation error:  Can't convert T[] to IFoo[]
    }

    public void InheritanceTest()
    {
        IBar[] variable = new IBar[0];
        ArrayMethod(variable);
    }

    public void ArrayMethod(IFoo[] args) { }
}
like image 938
Josh Avatar asked Dec 11 '15 19:12

Josh


People also ask

How do you pass an array of data?

Answer: An array can be passed to a function by value by declaring in the called function the array name with square brackets ( [ and ] ) attached to the end. When calling the function, simply pass the address of the array (that is, the array's name) to the called function.

Can we pass array in C++?

C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.

What is passing array in Java?

You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.

What is passing an array by reference?

If we pass the address of an array while calling a function, then this is called function call by reference. The function declaration should have a pointer as a parameter to receive the passed address, when we pass an address as an argument.


1 Answers

It's because array covariance, i.e., the fact that MySubtype[] is a subtype of MyType[], only works for reference types. The class constraint ensures that T is a reference type.

(Note that, in retrospect, array covariance is considered to be a bad idea. Try to avoid it if you can, for example, by making ArrayMethod generic or by using IEnumerable<IFoo> instead.)

like image 167
Heinzi Avatar answered Nov 02 '22 22:11

Heinzi