Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can't overload operators for existing types, as that could potentially break any other code that uses the types.</p> <p>You can make your own class that encapsulates an array, expose the methods and properties that you need from the array, and overload any operators that makes sense.</p> <p>Example:</p> <pre><code>public class AddableArray&lt;T&gt; : IEnumerable&lt;T&gt; { private T[] _array; public AddableArray(int len) { _array = new T[len]; } public AddableArray(params T[] values) : this((IEnumerable&lt;T&gt;)values) {} public AddableArray(IEnumerable&lt;T&gt; values) { int len; if (values is ICollection&lt;T&gt;) { len = ((ICollection&lt;T&gt;)values).Count; } else { len = values.Count(); } _array = new T[len]; int pos = 0; foreach (T value in values) { _array[pos] = value; pos++; } } public int Length { get { return _array.Length; } } public T this[int index] { get { return _array[index]; } set { _array[index] = value; } } public static AddableArray&lt;T&gt; operator +(AddableArray&lt;T&gt; a1, AddableArray&lt;T&gt; a2) { int len1 = a1.Length; int len2 = a2.Length; AddableArray&lt;T&gt; result = new AddableArray&lt;T&gt;(len1 + len2); for (int i = 0; i &lt; len1; i++) { result[i] = a1[i]; } for (int i = 0; i &lt; len2; i++) { result[len1 + i] = a2[i]; } return result; } public IEnumerator&lt;T&gt; GetEnumerator() { foreach (T value in _array) { yield return value; } } IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _array.GetEnumerator(); } } </code></pre> <p>Usage:</p> <pre><code>// create two arrays AddableArray&lt;int&gt; a1 = new AddableArray&lt;int&gt;(1, 2, 3); AddableArray&lt;int&gt; a2 = new AddableArray&lt;int&gt;(4, 5, 6); // add them AddableArray&lt;int&gt; result = a1 + a2; // display the result Console.WriteLine(string.Join(", ", result.Select(n=&gt;n.ToString()).ToArray())); </code></pre> <p>(Note that as the class implements <code>IEnumerable&lt;T&gt;</code>, you can use extension methods like <code>Select</code> on it.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload