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) { }
}
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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With