C# Extend array type to overload operators

Posted by Episodex on Stack Overflow See other posts from Stack Overflow or by Episodex
Published on 2009-11-26T16:34:04Z Indexed on 2010/04/07 1:23 UTC
Read the original article Hit count: 321

I'd like to create my own class extending array of ints. Is that possible? What I need is array of ints that can be added by "+" operator to another array (each element added to each), and compared by "==", so it could (hopefully) be used as a key in dictionary.

The thing is I don't want to implement whole IList interface to my new class, but only add those two operators to existing array class.

I'm trying to do something like this:

class MyArray : Array<int>

But it's not working that way obviously ;).

Sorry if I'm unclear but I'm searching solution for hours now...

UPDATE:

I tried something like this:

class Zmienne : IEquatable<Zmienne>
{
    public int[] x;
    public Zmienne(int ilosc)
    {
        x = new int[ilosc];
    }
    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }
        return base.Equals((Zmienne)obj);
    }
    public bool Equals(Zmienne drugie)
    {
        if (x.Length != drugie.x.Length)
            return false;
        else
        {
            for (int i = 0; i < x.Length; i++)
            {
                if (x[i] != drugie.x[i])
                    return false;
            }
        }
        return true;
    }

    public override int GetHashCode()
    {
        int hash = x[0].GetHashCode();
        for (int i = 1; i < x.Length; i++)
            hash = hash ^ x[i].GetHashCode();
        return hash;
    }

}

Then use it like this:

Zmienne tab1 = new Zmienne(2);
Zmienne tab2 = new Zmienne(2);
tab1.x[0] = 1;
tab1.x[1] = 1;

tab2.x[0] = 1;
tab2.x[1] = 1;

if (tab1 == tab2)
    Console.WriteLine("Works!");

And no effect. I'm not good with interfaces and overriding methods unfortunately :(. As for reason I'm trying to do it. I have some equations like:

x1 + x2 = 0.45
x1 + x4 = 0.2
x2 + x4 = 0.11

There are a lot more of them, and I need to for example add first equation to second and search all others to find out if there is any that matches the combination of x'es resulting in that adding.

Maybe I'm going in totally wrong direction?

© Stack Overflow or respective owner

Related posts about c#

Related posts about arrays