When setting up a request object for a web service, I need to dynamically add elements to some arrays.
I was hoping to simplify it by introducing an extension method:
public static class ArrayExtensions<T> where T : class { public static T[] Extend<T>(T[] originalArray, T addItem) { if (addItem == null) { throw new ArgumentNullException("addItem"); } var arr = new[] { addItem }; if (originalArray == null) { return arr; } return originalArray.Concat(arr).ToArray(); } }
So this old code:
if (foo.bazArr == null) { foo.bazArr = new[] { baz }; } else { foo.bazArr = new[] { baz }.Concat(foo.bazArr).ToArray();
can be rewritten as:
foo.bazArr = foo.bazArr.Extend(baz);
Error: 'System.Array' does not contain a definition for 'Extend' and no extension method 'Extend' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)
While the extension method is called like this:
foo.bazArr = ArrayExtensions<someService.bazType>.Extend(foo.bazArr, baz);
compiles great.
Why is this so? Why can't the compiler infer a type by itself if the array is strongly typed?
EDIT is the correct code below:
public static class ArrayExtensions { public static T[] Extend<T>(this T[] originalArray, T addItem) where T : class { if (addItem == null) { throw new ArgumentNullException("addItem"); } var arr = new[] { addItem }; if (originalArray == null) { return arr; } return originalArray.Concat(arr).ToArray();
For this popular question, here is another good simple example:
public static class Extns {
and when using.
someArrayOfSoundEffects.AnyOne().Play(); someArrayOfAnimations.AnyOne().BlendLeft(); winningDisplay.text = successStringsArray.AnyOne() +", " +playerName; SpawnEnormousRobotAt( possibleSafeLocations.AnyOne() );
etc. For any array, it will give you one random element. Used constantly in games for random effects, etc. An array can be of any type.