First of all i have some legacy .NET 2
code and i need to transform a extension function to a simple function. So i will start from what i want to achieve.
I have two object arrays which can be any object like int
for example
int[] a = new int[] { 1, 2, 3 };
int[] b = new int[] { 4, 5, 6 };
And the only thing i want to do is this:
var y = Concat(a, b);
and then return an array.
The problem is i can't figure out the correct combination in order to transform the following function.
public static class GenericExt
{
public static T Concat<T>(this T[] args, T[] args2)
{
if (!typeof(T).IsArray) throw new ArgumentException("Concat accepts only arrays");
Type elementType = typeof(T).GetElementType();
Array array = Array.CreateInstance(elementType, args.Length + args2.Length);
args.CopyTo(array, 0);
args2.CopyTo(array, args.Length);
return (T)(object)array;
}
}
Any corrections and help are appreciated.
And the only thing i want to do is this:
var y = Concat(a, b);
and then return an array.
You can't do that unless you're within the same class as the method (or a subclass). You can stop it being an extension method just by removing the this
part from the parameter list - but the call would have to be:
var y = GenericExt.Concat(a, b);
Another alternative would be to supply your own ExtensionAttribute
class (in the right namespace), and just keep using it as an extension method. The only thing in the framework that is needed for extension methods is that attribute, and you can just copy the declaration out of MSDN. Note that it will then cause problems if you refer to the library from .NET 3.5+ libraries/applications, where the attribute is part of the framework... but if everything is .NET 2, then you should be fine.
Note that the implementation is broken at the moment - at execution time, you're only accepting type arguments which are also arrays... so you'd actually need to pass in an int[][]
(with T
being int[]
) for it to work. You probably just want:
public static T[] Concat<T>(T[] args, T[] args2)
{
T[] array = new T[args.Length + args2.Length];
args.CopyTo(array, 0);
args2.CopyTo(array, args.Length);
return array;
}
But this is a bug in the current implementation which has nothing to do with it being an extension method.
See more on this question at Stackoverflow